Module: EasySearch::InstanceMethods

Defined in:
lib/easy_search/core.rb

Instance Method Summary collapse

Instance Method Details

#initialize(klass) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/easy_search/core.rb', line 25

def initialize(klass)
  @klass = klass
  
  # validate that the class derived from the missing method descends from
  # ActiveRecord and has been "configured" in `Setup.config { setup_tables {...} }'
  # (i.e. "Search.userz.with(...)" where "userz" is an invalid model)
  Validations.validate_class!(@klass)
end

#with(keywords, options = {}) ⇒ Object

used to collect/parse the keywords that are to be searched, and return the search results (hands off to the Rails finder)

Example:

Search.users.with("ryan heath")
# => <#User ... > or []


40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/easy_search/core.rb', line 40

def with(keywords, options={})
  search_terms = keywords.match(/"(.+)"/) ? extract($1, :exact => true) : extract(keywords)
  return [] if search_terms.blank?
  
  klass = to_model(@klass)
  
  conditions = "(#{build_conditions_for(search_terms)})"
  conditions << " AND (#{options[:conditions]})" unless options[:conditions].blank?
  sanitized_sql_conditions = klass.send(:sanitize_sql_for_conditions, conditions)

  options = { :select => 'DISTINCT *', :conditions => sanitized_sql_conditions, :order => options[:order], :limit => options[:limit] }
  options.update :include => associations_to_include
  klass.find(:all, options)
end