Dirk Bergmann

Developer, panographer. Does consultancy work from own company. Lives in Chiang Mai, Thailand.

Twitter

Chiang Mai

Hua Hin

Thailand Hotels

ListVote - List. Vote. Learn.

Partnerseek - Find Partners

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

/widget/8/edit

would become

/de/widget/8/edit

and

/

would become

/de/

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

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):

app/views/shared/_little_flags.html.erb

<%  {: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.