Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set locale automatically in ruby on rails [duplicate]

how to set locale automatically on ruby on rails? For instance, if the web pages is opened up in Spain then the locale=es, similarly if it is in united kingdom then the locale=en and alike?

Please help me out.

like image 642
RajG Avatar asked Nov 09 '12 15:11

RajG


2 Answers

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
like image 114
MrYoshiji Avatar answered Nov 07 '22 02:11

MrYoshiji


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
like image 45
Nick Ginanto Avatar answered Nov 07 '22 02:11

Nick Ginanto