Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Setting rails locale from domain name in rails for internationalization

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 311
    Comment on it


    Rails Internationalization : Setting locale from Domain Name

    For translating your application to other language, you can set I18n.default_locale to your locale in application.rb or in initializers as I told in my previous blog Configuring i18N Api in rails for internationalization. But if you want to support more than one locales, you need to pass locales in between requests. There are plenty of methods available like using before_filter, passing it with url or through domain names. In this article I am going to tell, how to set locales from domain names.
    As you already know that domains are generally geographically specific, so if you find .ru in url, you can easily recognize that it is russian and if you find .pt, it means Portuguese. Thus top-level domain can be used for translation. You can implement this in you application controller as:

    before_filter :place_locale
     
    def place_locale
      I18n.locale = get_locale || I18n.default_locale
    end
     
    # Get locale from top-level domain or return nil if such locale is not available
    # in your /etc/hosts file to try this out locally
    
    def get_locale
      desired_locale = request.host.split('.').last
      I18n.available_locales.include?(desired_locale.to_sym) ? desired_locale : nil
    end
    


    You can also set locale in subdomain similarly:

    # Get locale code from request subdomain (like http://pt.application.local:3000)
    def get_locale_subdomain
      desired_locale = request.subdomains.first
      I18n.available_locales.include?(desired_locale.to_sym) ? desired_locale : nil
    end
    


    You can done local switching using:

    link_to("Portuguese", "#{APP_CONFIG[:portuguese_web_url]}#{request.env['REQUEST_URI']}")
    


    It is beneficial and very easy if you are able to do provide different domains and different localizations. Hope you liked this also. The other way of achieving this problem is setting the locale from URL params, that I will tell in my next article, which will be available in the link given below.
    Setting the Locale from the URL Params

 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: