class Presenting::Search

Public Instance Methods

fields() click to toggle source
# File lib/presenting/search.rb, line 32
def fields
  @fields ||= FieldSet.new
end
fields=(obj) click to toggle source

I want to support three configuration formats:

Search.new(:fields => [:first_name, :last_name, :email])

Search.new(:fields => {
 'first_name' => :equals,
 'last_name' => :begins_with,
 'email' => :not_null
})

Search.new(:fields => {
 'fname' => {:sql => 'first_name', :pattern => :equals},
 'lname' => {:sql => 'last_name', :pattern => :begins_with},
 'email' => {:sql => 'email', :pattern => :not_null}
})
# File lib/presenting/search.rb, line 20
def fields=(obj)
  case obj
  when Array
    obj.each do |name| fields << name end
    
  when Hash
    obj.each do |k, v|
      fields << {k => v}
    end 
  end
end
to_sql(params, type = :simple) click to toggle source
# File lib/presenting/search.rb, line 36
def to_sql(params, type = :simple)
  send("to_#{type}_sql", params) unless params.blank?
end

Protected Instance Methods

to_field_sql(field_terms) click to toggle source

handles a search setup where a user may enter a search value for any field, and anything entered must match. this is usually presented to the user as a set of labeled search boxes.

example field terms:

field_terms = {
  'first_name' => {:value => 'Bob'}
  'last_name' => {:value => 'Smith'}
}
# File lib/presenting/search.rb, line 59
def to_field_sql(field_terms)
  searched_fields = fields.select{|f| field_terms[f.name] and not field_terms[f.name][:value].blank?}
  unless searched_fields.empty?
    sql = searched_fields.map(&:fragment).join(' AND ')
    binds = searched_fields.collect{|f| f.bind(field_terms[f.name][:value])}

    [sql, binds].flatten.compact
  end
end
to_simple_sql(term) click to toggle source

handles a simple search where a given term is matched against a number of fields, and can match any of them. this is usually presented to the user as a single “smart” search box.

# File lib/presenting/search.rb, line 44
def to_simple_sql(term)
  sql = fields.map(&:fragment).join(' OR ')
  binds = fields.collect{|f| f.bind(term)}.compact
  [sql, binds].flatten.compact
end