Module: Hammock::Suggest::ClassMethods

Defined in:
lib/hammock/suggest.rb

Instance Method Summary collapse

Instance Method Details

#suggest(given_fields, queries, opts = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/hammock/suggest.rb', line 12

def suggest given_fields, queries, opts = {}
  if (fields = given_fields & columns.map(&:name)).length != given_fields.length
    log "Invalid columns #{(given_fields - fields).inspect}."
  else
    field_names = fields.map {|f| "#{table_name}.#{f}" }
    opts[:limit] ||= 15
    opts[:order] ||= field_names
    find(:all,
      :select => sanitize_sql_array([
        "DISTINCT #{table_name}.*" +
        fields.zip(field_names).map {|f,f_name|
          (["  (STRPOS(LOWER(#{f_name}), ?) + 99) % 100"] * queries.length).
            join(",\n").
            start_with(",\nLEAST(\n").
            end_with(") AS #{f}_suggest_order")
        }.join.end_with("\n")
      ].concat(([queries] * fields.length).flatten)),
      :limit => (opts[:limit] unless opts[:limit].zero?),
      :order => fields.map {|f| "#{f}_suggest_order" }.concat(opts[:order]).join(', '),
      :conditions => [
        (["LOWER(#{field_names.join(' || ')}) LIKE ?"] * queries.length).join(' AND ')
      ].concat(queries.map{|q| "%#{q}%" })
    )
  end
end