Download

The latest version of SearchAPI can be found at

Documentation can be found at

Installation

The preferred method of installing SearchAPI is through the following command:

$ script/plugin install svn://rubyforge.org/var/svn/searchapi

License

SearchAPI is released under the MIT license.

SearchApi

Look at following Rails expression, which look for 34 years-old men:

Person.find(
  :all,
  :conditions => {:sex => 'M',
                  :birth_date => (Date.today-34.years)..
                                 (Date.today-33.years+1.day))

That’s a pretty handy way to avoid using heavy SQL expressions like:

Person.find(
  :all,
  :conditions => ['sex = ? AND birth_date BETWEEN ? AND ?,
                  'M',
                  (Date.today-34.years),
                  (Date.today-33.years+1.day)])

SearchApi plugin pushes the concept a step further, allowing you to define custom search keys that you can use in these condition hashes:

Person.find(
  :all,
  :conditions => { :male => true, :age => 34 })

Or, why not:

Person.find(
  :all,
  :conditions => { :thirty_four_aged_men => true })

This last expression would return people matching whatever condition is held by the “thirty_four_aged_men” concept.

SearchApi allows for defining Search API through SQL encapsulation, thanks to those keys in conditions hashes that are decoupled from actual underlying columns.

Example

Let’s define the :male and :age search keys:

class Person < ActiveRecord::Base
  has_search_api

  # define age search key
  search :age do |search|
    { :conditions => ['birth_date BETWEEN ? AND ?',
                      (Date.today-search.age.years),
                      (Date.today-(search.age-1).years+1.day)]}
  end

  # define male search key
  search :male do |search|
    { :conditions => ['sex = ?', if search.male then 'M' else 'F' end]}
  end
end

Navigate in this documentation

  • Learn how to add your own search keys

    Jump directly to the documentation of ActiveRecord::Base and its has_search_api method.

  • Learn about which search keys are automatically defined

    When your model calls has_search_api, many handy search keys are automatically defined: go look at SearchApi::Bridge::ActiveRecord and its method automatic_search_attribute_builders.

  • Dig further into SearchApi plugin

    Learn about:

    • bridges: SearchApi::Bridge::Base allows any class to be searchable;

    • ActiveRecord bridge: SearchApi::Bridge::ActiveRecord implements ActiveRecord searchable capabilities;

    • ActiveRecord integration: SearchApi::Integration::ActiveRecord that ties all together, allowing you to extend conditions hashes.