Setting User’s Locale Based on Domain Name In Rails
June 18th, 2009
In this tutorial I will show how you can quickly set the user’s locale based on the domain name they use to access your website. Let us assume you have your app, and you also own your own domain in several different country TLD’s, let’s say, you have example.com (main site), example.co.uk, example.fr, example.it example.es, and example.de.
When a user visits www.example.de in their browser, it makes sense that your app should default to showing the user the German (.de) translation of the website.
Here’s how to do it.
First of all, you will need a list of what locale translations are available to use at the current time. To do this, we will create a new file in config/initializers/locales.rb. This will automatically be loaded and parsed when your application starts.
config/initializers/locales.rb:
# # Build map of domain extensions and their corresponding language. # array contains: domain extension, locale # DEFAULT_LANGUAGE_BY_DOMAIN = [] DEFAULT_LANGUAGE_BY_DOMAIN << ["com", "en"] DEFAULT_LANGUAGE_BY_DOMAIN << ["uk", "en"] DEFAULT_LANGUAGE_BY_DOMAIN << ["de", "de"] DEFAULT_LANGUAGE_BY_DOMAIN << ["fr", "fr"] DEFAULT_LANGUAGE_BY_DOMAIN << ["it", "it"] DEFAULT_LANGUAGE_BY_DOMAIN << ["es", "es"]
Now add the following to your app/controllers/application_controller.rb:
# Setup the locale based on the domain name used to access the website
before_filter :set_locale
def set_locale
# Choose default locale of english
I18n.default_locale = 'en'
# Extract domain extension
this_domain_ext = request.host.split('.').last
# Search for domain extension in possible exts array, then
# set the language of the domain if a record is found.
this_domain_lang = DEFAULT_LANGUAGE_BY_DOMAIN.assoc(this_domain_ext)
if this_domain_lang then
I18n.locale = this_domain_lang[1]
end
# Allow a URL param to override everything else
if params[:locale] then
I18n.locale = params[:locale]
end
end
And that's it, all done!
When a user lands your website they will automatically have the correct locale selected for them!
This method also allows a nifty trick for the developer to test with. You can access your German translation on your localhost test site by appending the "locale=xx" query parameter to the URL, for example http://localhost:3000/?locale=de. Great for just quickly checking how something looks while developing.
Categories: Rails, User Experience
Most People subscribe via RSS Feed
Add to del.icio.us
Stumble It
damn, what a verbose and yet hairy code!
DEFAULT_LANGUAGE_BY_DOMAIN = {
“com” => “en”,
“uk” => “en”,
“ru” => “ru”,
…
}
# Setup the locale based on the domain name used to access the website
before_filter :set_locale
def set_locale
this_domain_ext = request.host.split(‘.’).last
I18n.locale = params[:locale] ||
DEFAULT_LANGUAGE_BY_DOMAIN[this_domain_ext] ||
‘en’
end
I think I will try to recommend this post to my friends and family, cuz it’s really helpful.