Module: NaiveSearch::NaiveSearchOn::ClassMethods

Defined in:
lib/naive-search/naive_search_on.rb

Instance Method Summary collapse

Instance Method Details

#naive_search_on(*fields) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/naive-search/naive_search_on.rb', line 8

def naive_search_on(*fields)
  if fields.size.zero?
    raise "No arguments given, please specify which fields should be indexed and searched."
  end
  options = (fields).extract_options!
  @order = options[:order] || "id desc"
  @limit = options[:limit] || 100
          
  cattr_accessor :naive_search_fields
  cattr_accessor :naive_search_index_field
  self.naive_search_fields = fields
  self.naive_search_index_field = options[:naive_search_index_field] || :naive_search_index
  self.before_save :update_naive_search_index
end

#search_for(query, page_no = 1, page_size = nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/naive-search/naive_search_on.rb', line 23

def search_for(query, page_no = 1, page_size = nil)
  words = ::UnicodeUtils.downcase(query.to_s).split " "
  conditions = words.map do |w|
    replace_bind_variables("#{self.naive_search_index_field} like ?", ["%#{w}%"])
  end.join " OR "
  
  page_size ||= @limit
  offset = (page_no * page_size) - page_size
          
  self.where(conditions).order(@order).limit(page_size).offset(offset).sort do |a,b|
    b.relevance_for(query) <=> a.relevance_for(query)
  end
end