Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Setting rails locals from Client Requests

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 389
    Comment on it


    Rails Internationalization : Setting locals from Client Requests

    Hi friends, in my previous blog, we looked into Setting the Locale from the URL Params. There are some more cases where we don't want to set the locales through URLs or domains. We want the locale to be set by the client as per his wish. It can be based on the geographical location of the user, that can be achieved through his IP or user himself specifies it by selecting and saving a particular language locale available in his profile. It can be seen under following: -

    (a) Using Accept-Language: -
    Accept-Language HTTP header can be used to supply client information. It can be set in the browser or in curl request. A sample of it is as given:

    def set_locale
      logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
      I18n.locale = get_locale_from_accept_header
      logger.debug "* Locale set to '#{I18n.locale}'"
    end
     
    private
      def get_locale_from_accept_header
        request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
      end
    


    On production environment you can use a gem such as Iain Hecker's http_accept_language or even Rack middleware such as Ryan Tomayko's locale.

    (b) Using GeoIP (or Similar) Database: -
    In this approach, you need to get the IP of the user from the database or from request environment and then you can find the location of the user from that IP and set the locale according to that IP.

    (c) User Profile: -
    In this approach you can allow user to select a locale from a given list and let him save it to his profile, so according to that, user preferred locale would be served from the next time.

    Hope you like this article. For more like this Click here

 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: