Module: Ximate::ClassMethods

Defined in:
lib/ximate/search.rb

Instance Method Summary collapse

Instance Method Details

#asearch(pattern) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ximate/search.rb', line 38

def asearch(pattern)
  table = self.table_name.to_sym
  matches = {} # {id => rank, id => rank}
  lastsearch = {} # Save last 'e' search for every word in pattern to avoid multi-search of the same word
  pattern.split(' ').each { |w| lastsearch[w] = -1 }
  DATA[I18n.locale] ||= {}
  DATA[I18n.locale][table] ||= {}
  DATA[I18n.locale][table].each do |word, ids_ranks|
    pattern.split(' ').each do |w|
      if w.size > OPTIONS[:ignore_word_short_than]
        if e = Fuzzy.equal(word, w.downcase, OPTIONS[:match_error_percent])
          if e > lastsearch[w]
            lastsearch[w] = e
            Rails.logger.debug("XIMATE asearch: '#{word}' match with '#{w}' (e = #{e})") if OPTIONS[:debug]
            ids_ranks.each { |id, rank| matches[id] = matches[id].to_i + (e**rank) }
          end
        end
      end
    end
  end
  return where('1 = 0') if matches.empty?
  rel = scoped
  rel.ranks = matches
  rel.where("#{table}.id IN (#{matches.keys.join(',')})")
  # select("*, #{gen_if_select(matches)} AS RANK").where("#{table}.id IN (#{matches.keys.join(',')})")
end