BakerStreet

class UfoSearch < BakerStreet::Base
  include BakerStreet::ActiveRecord

  search_in 'Spacecraft'
  default_scope { where(:identifier => nil).includes(:spaceport) }

  has_criterion(:color)     {|q| where color: [q, "dark_#{q}", "light_#{q}"] }
  has_criterion(:min_size)  {|q| where 'size > ?', q }

  has_criterion(:spaceport) {|q| joins(:spaceport).where(spaceport: { name: q }) }
end
UfoSearch.new(params[:q]).search

Features

ORMs

BakerStreet only supports ActiveRecord for now. Mongoid is planned to be supported ASAP.

Search Engines

Sphinx is the first supported search engine. Help is welcome to support other search engines (Elaticsearch, Solr).

Sphinx

class UfoSearch < BakerStreet::Base
  include BakerStreet::ActiveRecord
  include BakerStreet::Sphinx

  # Not yet supported
  # define_index do
  #   indexes name
  # end
  #
  # sphinx_options do
  #   max_matches 1000
  #   per_page    1000
  # end

  self.sphinx_options = { max_matches: 100, per_page: 100 }

  has_criterion(:name) {|q| where(id: search_for_ids(name: "*#{q}*")) }
end

Extensions

Pagination

BakerStreet supports Kaminari and WillPaginate syntaxes :

Kaminari example :

@search = UfoSearch.new(params[:q]).page(params[:page]).per(50)
paginate @search

Decorator

BakerStreet provides a simple decorator.

class UfoSearch < BakerStreet::Base
  include BakerStreet::Decorator

  decorates(:shape)     {|ufo| I18.t ufo.shape, scope: 'ufos.shapes' }
  decorates(:martian?)  {|ufo| ufo.planet? && ufo.planet.name == 'Mars' }
end
@search = UfoSearch.new params[:q]
@search.decorate.each do |result|
  puts [result.id, result.shape, result.martian?]
end

Custom extension

You can provides your own extension. The following example optimizes geocoding of your results.

require 'geocoder'

module MassGeocoder
  def geocode
    results.each {|result| result.geocode unless result.geocoded? }
    self
  rescue SocketError, TimeoutError => e
    warn "Geocoding failed for #{self.inspect}"
    self
  end
end

class UfoSearch < BakerStreet::Base
  include MassGeocoder
end
UfoSearch.new(params[:q]).geocode.each do |result|
  puts [result.id, result.to_coordinates]
end

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request