在我的Rails应用程序中使用的语言环境。 我有以下的routes.rb
scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
root to: 'static_pages#home'
devise_for :users, :controllers => { :registrations => :registrations }
resources :blogs do
resources :comments
end
get 'tags/:tag', to: 'blogs#index', as: :tag
resources :users
get '/users/subregion_options' => 'users#subregion_options'
resources "contacts", only: [:new, :create]
match '/crew', to: 'static_pages#crew', via: 'get'
....
end
match '*path', to: redirect("/#{I18n.locale}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" }, via: 'get'
我想访问该页面的用户重定向到依赖于语言的浏览器设置(HTTP标头)的语言环境。 这一切工作 - 基本。 但是,访问本地主机:3000 / application_controller.rb不会被调用-therefore的set_locale没有被执行,这意味着用户与欢迎轨页结束
我怎么可以强制set_locale被称为?
class ApplicationController < ActionController::Base
before_filter :set_locale
def set_locale
if params[:locale].blank?
redirect_to "/#{extract_locale_from_accept_language_header}"
else
I18n.locale = params[:locale]
end
end
private
def extract_locale_from_accept_language_header
case request.env['HTTP_ACCEPT_LANGUAGE'].try(:scan, /^[a-z]{2}/).try(:first).try(:to_sym)
when 'en'
'en'
when 'de'
'de'
when 'de-at'
'de'
when 'de-ch'
'de'
else
'en'
end
end
def default_url_options(options = {})
{locale: I18n.locale}
end