Module: Searchlight::Adapters::ActiveRecord::Search

Defined in:
lib/searchlight/adapters/active_record.rb

Instance Method Summary collapse

Instance Method Details

#model_has_db_attribute?(attribute_name) ⇒ Boolean

The idea here is to provide a means to allow users to bypass the check if it causes problems (e.g. during ‘rake assets:precompile` if the DB has yet to be created). To bypass this, a user could monkey patch as follows:

module Searchlight::Adapters::ActiveRecord::Search
  def model_has_db_attribute?(attribute_name)
    model_class_for(search_target).columns_hash.keys.include?(attribute_name)
  rescue StandardError
    true
  end
end

Alternatively, they could monkey-patch Searchlight::Adapters::ActiveRecord::Search::model_has_db_attribute to simply always return true, though they would then not get the benefit of the improved error messaging.

Returns:

  • (Boolean)


59
60
61
# File 'lib/searchlight/adapters/active_record.rb', line 59

def model_has_db_attribute?(attribute_name)
  model_class_for(search_target).columns_hash.keys.include?(attribute_name)
end

#searches(*attribute_names) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/searchlight/adapters/active_record.rb', line 12

def searches(*attribute_names)
  super

  # Ensure this class only adds one search module to the ancestors chain
  if @ar_searches_module.nil?
    @ar_searches_module = Named::Module.new("SearchlightActiveRecordSearches(#{self})")
    include @ar_searches_module
  end

  eval_string = attribute_names.map { |attribute_name|
    model_class = model_class_for(search_target)
    if model_has_db_attribute?(attribute_name.to_s)

      <<-UNICORN_BILE
      def search_#{attribute_name}
        search.where('#{attribute_name}' => public_send("#{attribute_name}"))
      end
      UNICORN_BILE
    else
      <<-MERMAID_TEARS
      def search_#{attribute_name}
        raise Searchlight::Adapters::ActiveRecord::UndefinedColumn,
        "Class `#{model_class}` has no column `#{attribute_name}`; please define `search_#{attribute_name}` on `\#{self.class}` to clarify what you intend to search for"
      end
      MERMAID_TEARS
    end

  }.join

  @ar_searches_module.module_eval(eval_string, __FILE__, __LINE__)
end