Add locale switcher, by query parameter(?lang=xx) or Accept-Language header

This commit is contained in:
uu59 2014-05-27 17:54:01 +09:00
parent ac97d34c9c
commit b9405fd937
2 changed files with 27 additions and 1 deletions

View File

@ -4,6 +4,7 @@ class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user
before_action :login_required
before_action :set_locale
def current_user
return unless session[:remember_token]
@ -20,4 +21,29 @@ class ApplicationController < ActionController::Base
def find_fluentd
@fluentd = Fluentd.find(params[:fluentd_id])
end
def set_locale
available = I18n.available_locales.map(&:to_s)
if params[:lang] && available.include?(params[:lang])
session[:prefer_lang] = params[:lang]
I18n.locale = params[:lang]
return
end
if session[:prefer_lang]
I18n.locale = session[:prefer_lang]
return
end
# NOTE: ignoring q=xxx in request header for now
return if request.env["HTTP_ACCEPT_LANGUAGE"].blank?
langs = request.env["HTTP_ACCEPT_LANGUAGE"].gsub(/q=[0-9.]+/, "").gsub(";","").split(",")
prefer = langs.find {|lang| available.include?(lang) }
unless prefer
if langs.find{|lang| lang.match(/^en/)}
I18n.locale = :en
return
end
end
I18n.locale = prefer
end
end

View File

@ -30,7 +30,7 @@ module FluentdUi
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = 'ja'
config.i18n.default_locale = 'en'
config.autoload_paths += %W(#{config.root}/app/workers #{config.root}/lib)
config.after_initialize do
# http://qiita.com/tanaka51/items/c8873319689217bb81a9