views:

921

answers:

2

I am adding I18N to my rails application by passing the locale using url params. My urls are looking like http://example.com/en/users and http://example.com/ar/users (for the english and arabic locales respectively).

In my routes file, I have defined my routes with a :path_prefix option:

map.resources :users, :path_prefix => '/:locale'

And locale is being set using a before_filter defined in ApplicationController

def set_locale
    I18n.locale = params[:locale]
end

I also defined ApplicationController#default_url_options, to add locale to all urls generated by the application:

def default_url_options(options={})
    {:locale => I18n.locale}
end

What I want is to add a link in the layout header (displayed in all pages) that would link to the same page but with the other locale.

For instance, if I am browsing the arabic locale, I want a "English" link in the header, that will redirect me back to my current page, and set the locale to english. Is there a way to do this in rails?

+1  A: 

You can parse request_uri, and replace your locale in the path with regular expression

Ok, here is helper example. If I correctly understand the goal

def locale_url(url, locale)
  url.gsub(/\/\w*$/, "/#{locale}")
end

url = "http://www.domain.com/products/1/ru" # or request.request_uri
locale = "en"
locale_url(url, locale) #=> "http://www.domain.com/products/1/en"

This is a start point, so you can make some different stuff that you need

fl00r
I was hoping for some helper that would do that for me. But so far, this is the only solution I have found.I guess I'll do something like request.request_uri.gsub(/\/en\//, '/ar/')... That should do the trickThanx for the input
Faisal
Ok, I've added sample helper
fl00r
+4  A: 

Took me a while to find this but here is my solution:

link_to 'English', url_for( :locale => 'en' )
link_to 'Deutch', url_for( :locale => 'de' ) 

From the docs here: http://api.rubyonrails.org/classes/ActionController/Base.html#M000649

When generating a new URL, missing values may be filled in from the current request‘s parameters. For example, url_for :action => ‘some_action‘ will retain the current controller, as expected. This behavior extends to other parameters, including :controller, :id, and any other parameters that are placed into a Route‘s path.

So using url_for will default to the current request's parameters, just change the one's you want in your code. In this case all I changed was :locale, so everything else stays the same.

Note this also works for "hidden" :parameters. So if you have:

map.my_map ':locale/my_map', :controller => 'home', :action => 'my_map'

using the above url_for in the page /en/my_map will not have 'home' in the url (ie /en/home/my_map). Bonus.

pixelearth
Thanx, this would be an elegant solution. However, it is not working with restful urls :s
Faisal