Skip to content

Instantly share code, notes, and snippets.

@jcsky
Created July 25, 2016 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcsky/60cbac8ddb36b9d65a0b2fc7fa0c3bde to your computer and use it in GitHub Desktop.
Save jcsky/60cbac8ddb36b9d65a0b2fc7fa0c3bde to your computer and use it in GitHub Desktop.
set_i18n_locale_from_browser
class ApplicationController < ActionController::Base
before_action :set_locale
private
def set_locale
if current_user
if !current_user.locale.present?
set_i18n_locale_from_browser
current_user.update(locale: I18n.locale.to_s)
end
I18n.locale = current_user.locale
else
set_i18n_locale_from_browser
end
end
def set_i18n_locale_from_browser
old_locale = I18n.locale
begin
locale = (accept_locale(env) || I18n.default_locale).to_s
unless I18n.locale_available? locale
locale = locale.gsub(/(?<=-).+/, /(?<=-).+/.match(locale).to_s.upcase)
end
env['rack.locale'] = I18n.locale = locale
response.headers['Content-Language'] = locale unless response.headers['Content-Language']
ensure
I18n.locale = old_locale
end
end
def accept_locale(env)
accept_langs = env["HTTP_ACCEPT_LANGUAGE"]
return if accept_langs.nil?
languages_and_qvalues = accept_langs.split(",").map { |l|
l += ';q=1.0' unless l =~ /;q=\d+(?:\.\d+)?$/
l.split(';q=')
}
lang = languages_and_qvalues.sort_by { |(locale, qvalue)|
qvalue.to_f
}.last.first
lang == '*' ? nil : lang
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment