set locale automatically in ruby on rails

try using gem geocoder and i18n_data gem and have a before_filter to a method which does

def checklocale
  I18n.locale =  I18nData.country_code(request.location.country) 
end

You can implement it like this in your ApplicationController:

class ApplicationController < ActionController::Base
  before_filter :set_locale

  def set_locale
    I18n.locale = extract_locale_from_headers
  end

  private

  def extract_locale_from_headers
    request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first.presence || 'en'
  end
end

It will "inspect" the received request, find the language of the client's browser and set it as your I18n locale.

Take a look at the RubyOnRails Guide about I18n for further instructions.


I highly recommend to have a set of supported locales and fallback to a default locale. Something like this:

ALLOWED_LOCALES = %w( fr en es ).freeze
DEFAULT_LOCALE = 'en'.freeze

def extract_locale_from_headers
  browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
  if ALLOWED_LOCALES.include?(browser_locale)
    browser_locale
  else
    DEFAULT_LOCALE
  end
end