search_party

Rails params that actually mean something!

search_party parses a Rails request’s GET variables according to your own rules. This allows you to:

  • Keep your controllers skinny,

  • Remove models’ ID numbers from your URLs,

  • Prepare your query parameters for better use in searchlogic[http://github.com/binarylogic/searchlogic] by binarylogic.

Installation

In environment.rb:

Rails::Initializer.run do |config|
  config.gem 'laserlemon-search_party', :lib => 'search_party', :source => 'http://gems.github.com'
end

At your application root, run:

$ sudo rake gems:install

All the parameter parsing is application-defined, so you’ll also need an initializer. search_party adds three class variables to ActionController::Request:

  • search_parameter_models

  • search_parameter_finders

  • search_parameter_patterns

An example search_party initializer:

ActionController::Request.search_parameter_models = {
  :user => 'User',
  :friend => 'User',
  :home_state => 'State'
}

ActionController::Request.search_parameter_finders = {
  :user => :find_by_login,
  :friend => :find_by_login,
  :home_state => :find_by_abbreviation
}

ActionController::Request.search_parameter_patterns = [
  [/^\d+$/,                   lambda{|m| m.to_s.to_i }],
  [/^\d+\.\d+$/,              lambda{|m| m.to_s.to_f }],
  [/^(?:true|t|yes|y|on)$/i,  true],
  [/^(?:false|f|no|n|off)$/i, false],
  [/^\s+$/,                   nil]
]

Example

With search_party, a search_params hash is added to the controller instance in addition to the normal (and boring) params. The new search_params are available in the view as well, just like params, and are also accessible in the Request object via search_parameters. The search_params are simply the query parameters from a given request, run through the initializer configuration to silently make more sense out of what’s being really being asked for.

For instance, the following params:

{"friend" => "laserlemon", "home_state" => "WA"}

would product the following search_params:

{"friend" => #<User id: 1, first_name: "Steve", last_name: "Richert", login: "laserlemon">, "home_state" => #<State id: 48, name: "Washington", abbreviation: "WA">}

using User.find_by_login and State.find_by_abbreviation. With the search_parameter_patterns variable, non-model query parameters are also cleaned up:

{"price" => "12.50", "negotiable" => "no"}

produces:

{"price" => 12.5, "negotiable" => false}

Tips

  • search_parameter_patterns are evaluated in the order they’re defined.

  • Lambdas may be used as the value corresponding to a pattern, with the MatchData object being passed as a single argument.

  • search_party will parse the query parameters recursively in the case of multidimensional parameters.