Module: Ximate::ClassMethods

Defined in:
lib/ximate/search.rb

Instance Method Summary collapse

Instance Method Details

#asearch(pattern) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/ximate/search.rb', line 45

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 = where("#{table}.id IN (#{matches.keys.join(',')})")
  rel.ranks = matches
  return rel
  # select("*, #{gen_if_select(matches)} AS RANK").where("#{table}.id IN (#{matches.keys.join(',')})")
end