Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Setting Rails Locales from URL

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 502
    Comment on it


    Rails Internationalization : Setting locals from URL

    In my previous blog, we looked in Setting rails locale from domain name, it was a good approach of detecting the desired locale from domain or subdomain, but sometimes you are not able to provide different domains or subdomains for different locales. In that case the best option is to pass the locales in url as a parameter. Then we can have URL's like www.mysite.com/content?locales=pt or www.mysite.com/pt/content. By this approach we can simply use before_filter and set the locales according to the request as:

    before_action :apply_locale
     
    def apply_locale
      I18n.locale = params[:locale] || I18n.default_locale
    end
    


    Thus we can see getting a parameter and setting the required locale is not a tough task, but sending an explicit option in every url is actually hard. To solve this problem, rails has a infrastructure for "centralizing dynamic decisions about the URLs" in its ApplicationController#default_url_options, it gives us ability to set the defaults for url_for method. We can achieve this by including this in ApplicationController:

    # app/controllers/application_controller.rb
    def default_url_options(options = {})
      { locale: I18n.locale }.merge options
    end
    


    By using this each url will now automatically include locale in the query string like:http://www.mysite.com/?locale=pt. As here you can see the url is not looking good, so you want a url that looks like REST as www.mysite.com/pt/content. You can achieve this by overriding the default_url_option in routes by scooping.

    # config/routes.rb
    scope "/:locale" do
      resources :content
    end
    


    If you want locale to be optional as you don't want to send it with each request, you can do it like this:

    # config/routes.rb
    scope "(:locale)", locale: /pt|nl/ do
      resources :content
    end
    


    Thus you will be able to access contents directly without routing error. You also need to change the root url as:

    # config/routes.rb
    get '/:locale' => 'mysite#index'
    


    Hope you liked this, Check this also Setting the Locale from Client Requests

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: