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)