在 Rails w/o 资源范围内设置 RESTful 区域设置
set RESTful setting of locale in Rails w/o scoping of resources
基本上我的应用程序中有一个静态页面,其中 RESTful URL 指向已翻译的页面。
即
https://foo.bar/ja
我没有或不需要做任何事情
scope "/:locale" do
resources :books
end
我的 routes.rb
文件中的演习,因为它只是该特定区域设置中的一个亮点页面,而不是整个翻译网站的地图。
我明白,如果我将语言环境设置为 param
,那么它会很简单:
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
在我的应用程序控制器中。我在 ApplicationController
中从路径而不是参数中获取语言环境的等效语句是什么:
https://foo.bar/<locale-goes-here>
我试着查看这个:http://guides.rubyonrails.org/i18n.html 但在其中找不到对 RESTful 解决方案的这种特殊处理。
我可以这样做:
def set_locale
current_locale = 'en' # default one
parsed_locale = request.fullpath.split('/').last
parsed_locale = I18n.available_locales.map(&:to_s).include?(parsed_locale.to_s) ? parsed_locale : current_locale
I18n.locale = parsed_locale
end
基本上我的应用程序中有一个静态页面,其中 RESTful URL 指向已翻译的页面。
即
https://foo.bar/ja
我没有或不需要做任何事情
scope "/:locale" do
resources :books
end
我的 routes.rb
文件中的演习,因为它只是该特定区域设置中的一个亮点页面,而不是整个翻译网站的地图。
我明白,如果我将语言环境设置为 param
,那么它会很简单:
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
在我的应用程序控制器中。我在 ApplicationController
中从路径而不是参数中获取语言环境的等效语句是什么:
https://foo.bar/<locale-goes-here>
我试着查看这个:http://guides.rubyonrails.org/i18n.html 但在其中找不到对 RESTful 解决方案的这种特殊处理。
我可以这样做:
def set_locale
current_locale = 'en' # default one
parsed_locale = request.fullpath.split('/').last
parsed_locale = I18n.available_locales.map(&:to_s).include?(parsed_locale.to_s) ? parsed_locale : current_locale
I18n.locale = parsed_locale
end