How do you detect the users language (in RoR) as set in the browser? I will have a select box the user can use at anytime, but I\'d like to default to whatever their browser
This is a really old question, but I like to mention that Rails guide has a description of how to detect user browser language.
Below code is based on the solution from Ruby on Rails guide with improvements:
code:
def set_locale_based_on_browser
locale = extract_locale_from_accept_language_header
I18n.locale =
if locale_valid?(locale)
locale
else
:en
end
end
private
def locale_valid?(locale)
I18n.available_locales.map(&:to_s).include?(locale)
end
def extract_locale_from_accept_language_header
accept_language = request.env['HTTP_ACCEPT_LANGUAGE']
return unless accept_language
accept_language.scan(/^[a-z]{2}/).first
end
end
More information about locale detection can be found in Ruby on Rails guide: https://guides.rubyonrails.org/i18n.html#choosing-an-implied-locale