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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With