Module: SitemapSearch::Model::ClassMethods

Defined in:
lib/sitemap_search/model.rb

Instance Method Summary collapse

Instance Method Details

#search(query) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/sitemap_search/model.rb', line 24

def search(query)
  # split up the words in the query, clear out blank ones
  words = query.strip.downcase.split(" ").reject(&:blank?)
  # return no results if query was blank
  return [] if words.empty?
  # wrap each one in the matchers and replicate by the number of fields
  wrapped_words = words.map {|word| ["%#{word}%"] * self.search_fields.size }
  # Construct conditions for each field
  field_conditions = self.search_fields.map {|field| "LOWER(#{field}) LIKE ?"}
  # join them with with an OR
  fields_per_word = field_conditions.join(" OR ")
  # replicate the condition for each word, join them all with an AND
  all_conditions = ([fields_per_word] * words.size).map {|stmt| "(#{stmt})"}.join(" AND ")
  query_conditions = [all_conditions, wrapped_words].flatten
  find(:all, :conditions => query_conditions, :joins => includes)
end