07 JulDetect user's preferred language in rails 3 application
Thursday, 07 July 2011 — 15:13If you have/want to have a localized rails 3 application, this post is for you. You could implement this in the hard way: manually reading the Accept-Language header from your incoming request. That would be something like this:
def set_locale logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}" I18n.locale = extract_locale_from_accept_language_header logger.debug "* Locale set to '#{I18n.locale}'" end private def extract_locale_from_accept_language_header request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first end
Fortunately, there is an easy way. There is a great gem here you can use with a little of config so that you can use it in your rails 3 application.
Let’s start adding a new line to our Gemfile:
gem "http_accept_language", :git => 'git://github.com/iain/http_accept_language.git'
Then we need to require it from application_controller, or application_helper module:
module ApplicationHelper require 'http_accept_language' # Get user language from web request end
And finally, the code that makes use of it:
class ApplicationController < ActionController::Base before_filter :set_language def set_language # If the header language settings are supported, then use that as the default language... available = %w{en es} default_lang = request.compatible_language_from(available) I18n.locale = params[:language] || default_lang || I18n.default_locale end end
You will just need to have en.yml and es.yml files (spanish and english dictionaries) with translated keys. I have those files in default path “config/locales/”
Ger