Globalizing the Current URL in a Rails View

Rails I18n, globalize2 and Sven Fuchs’ routing_filter provide a nigh complete globalization solution for Rails, especially after the splendid new localized view support in Rails 2.3.

So I was looking for a way to display small flags found at famfamfam and link them to the “localized” versions of the current uri in all pages of the application, so that for example


would become




would become


Having said routing_filter installed, I created this little helper method in application_helper.rb:


def localize_current_path(locale) current_uri = request.env['PATH_INFO'] my_path = ActionController::Routing::Routes.recognize_path current_uri, :method => :get #above works only with :get, you could pass in the current method with :method => request.method.to_sym url_for(my_path.merge!(:locale => locale)) end

This code demonstrates:

  • getting the elements that make up the current route with ActionController::Routing::Routes.recognize_path, this method returns a hash

  • merging the locale into said hash

  • generating the new url with url_for

The helper can now be easily used in the view like so (code is adjusted for the famfamfam British flag whose name is gb.gif):


<% {:de => "Deutsch", :en => "English", :th =>"Thai"}.each_pair do |key, value| %> <%= link_to image_tag(“famfamfam/flags/gif/#{key == :en ? “gb” : key}.gif”, :alt => value, :title => value), localize_current_path(key) %> <%end%>

Hope it helps.

Posted: 16 September 2009

comments powered by Disqus