Query Key Translation Ruby on Rails Plugin (Rails Routing pt. 3)
- Posted by alex on June 20th, 2007 filed in work, ruby on rails
Translate query keys in Ruby on Rails with this Plugin.
After getting approval from the big boss, I’m now publishing my first rails plugin. This is a plugin I’ve previously talked about developing here and here.
The plugin extends Ruby on Rails route recognition/dispatching to allow controllers to refer to parameters passed in on the query portion of the URL with translated names. Additionally, URL generation via url_for and its helper methods like link_to have been extended to generate links with translated query keys. A single configuration within routes.rb allows this.
Note the ‘translates’ key/value pair added to each route definition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
ActionController::Routing::Routes.draw do |map| # Our old application accepted URLs like this. # We refer to the parameters as :page and :sort # in our new app, the old URLs will have ‘p’ and ’s’ map.connect ‘legacy_action.jsp‘, :controller => ‘legacy‘, :action => ‘action‘, :translates => {:p => :page} # we want urls like: http://example.com/search?q=Pizza+Hut&l=en map.connect ‘search‘, :controller => ‘search‘, :action => ‘search‘, :translates => {:q => :search_query, :l => :language} end |
In a view or controller, you would build links using the url_for helpers.
1 2 3 4 |
link_to “Pizza Hut“, :controller => ‘search‘, :action => ‘search‘, :search_query => ‘Pizza Hut‘, :language => ‘en‘ |
The generated URL looks like this:
http://example.com/search?q=Pizza+Hut&l=en
At route recognition/dispatch time, the plugin instantiates the params hash with variable names that are meaningful (:search_query, rather than :q) based on the configurations within routes.rb.
1 2 3 4 5 6 |
class SomeController < ApplicationController def search @search_query = params[:search_query] # “Pizza Hut” @language = params[:language] # “en” end end |
You can download the plugin here.
|
|
$> script/plugin install http://svn.alexle.org/translates |
Note: I haven’t confirmed whether this plugin will work for restful routes.
Leave a Comment