Skip to content

Commit

Permalink
Begin encasulating configuration in a class
Browse files Browse the repository at this point in the history
  • Loading branch information
ellnix committed Jan 8, 2025
1 parent 4597126 commit 7da3be4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
11 changes: 4 additions & 7 deletions lib/meilisearch-rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
require 'meilisearch/rails/multi_search'
require 'meilisearch/rails/index_settings'
require 'meilisearch/rails/safe_index'
require 'meilisearch/rails/model_configuration'

if defined? Rails
begin
Expand Down Expand Up @@ -73,7 +74,7 @@ class << base
alias_method :must_reindex?, :ms_must_reindex? unless method_defined? :must_reindex?
end

base.cattr_accessor :meilisearch_options, :meilisearch_settings
base.cattr_accessor :meilisearch_options, :meilisearch_settings, :ms_config
end

def meilisearch(options = {}, &block)
Expand All @@ -83,11 +84,9 @@ def meilisearch(options = {}, &block)
per_page: meilisearch_settings.get_setting(:hitsPerPage) || 20, page: 1
}.merge(options)

attr_accessor :formatted
self.ms_config = ModelConfiguration.new(model_name.to_s.constantize, options)

if options.key?(:per_environment)
raise BadConfiguration, ':per_environment option should be defined globally on MeiliSearch::Rails.configuration block.'
end
attr_accessor :formatted

if options[:synchronous] == true
if defined?(::Sequel::Model) && self < Sequel::Model
Expand All @@ -104,8 +103,6 @@ def meilisearch(options = {}, &block)
end
end
if options[:enqueue]
raise ArgumentError, 'Cannot use a enqueue if the `synchronous` option is set' if options[:synchronous]

proc = if options[:enqueue] == true
proc do |record, remove|
if remove
Expand Down
33 changes: 33 additions & 0 deletions lib/meilisearch/rails/model_configuration.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
module MeiliSearch
module Rails
class ModelConfiguration
attr_reader :model

def initialize(model, options = {})
@model = model
parse_options(options)
end

private

def parse_options(options)
refute_global_options(options, [:per_environment])
mutually_exclusive_options(options, [:enqueue, :synchronous])
end

def refute_global_options(options, misapplied_global_opts)
misapplied_global_opts.each do |opt|
if options[opt]
raise BadConfiguration, ":#{opt} option should be defined globally on MeiliSearch::Rails.configuration block."
end
end
end

def mutually_exclusive_options(options, exclusives)
first, second = exclusives.select { |opt| options[opt] }

raise ArgumentError, "Cannot use :#{first} if the :#{second} option is set" if second
end
end
end
end

0 comments on commit 7da3be4

Please sign in to comment.