Rails 4 中的语言环境回退不起作用

Locale fallbacks in Rails 4 not working

我正在为新加坡、马来西亚、台湾和中国的客户构建一个 Rails 4 站点。

马来西亚华人的区域设置代码是zh-MY

我想保留一组基础 zh-CN(简体中文)语言环境文件,以便 zh-MY 回退到 zh-CN

只有zh是不正确的,因为zh-TW(繁体中文)是台湾使用的,与zh-CN.

有很大区别

所以这是我的 config/application.rb 文件 as per the Rails Guide

require File.expand_path('../boot', __FILE__)

require 'rails/all'
require "i18n/backend/fallbacks"

module MyAwesomeApp
  class Application < Rails::Application
    I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)

    # all translations from config/locales/**/*.rb,yml are auto loaded.
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

    # The default locale is :en
    config.i18n.default_locale = :en

    # See http://guides.rubyonrails.org/i18n.html#localized-views for a discussion of
    # how language codes fall-back.
    config.i18n.available_locales = [:en, :'zh-CN', :'zh-TW', :'en-SG', :'en-MY', :'zh-MY']
    I18n.fallbacks.map(:'zh-MY' => :'zh-CN')
  end
end

但这根本行不通。

当我实际将语言环境设置为 :zh-MY 时,它不会退回到 :zh-CN 而是 :en

我错过了什么?

更新: 如果我 puts "I18n.fallbacks #{I18n.fallbacks}" 它说 I18n.fallbacks {}。显然 I18n.fallbacks.map 失败了。

更新 根据评论中的建议,我在检查 I18n.fallbacks 之后在下一行查看了 I18n.fallbacks[:'zh-MY'] 并且 returns [:"zh-MY", :zh, :"zh-CN", :en]

更新 在我的 application controller 中使用 binding.pry 我检查了语言环境等并观察到这一点:

[1] pry(#<ServicesController>)> I18n.locale
=> :"zh-MY"
[2] pry(#<ServicesController>)> I18n.fallbacks
=> {:en=>[:en], :"zh-MY"=>[:"zh-MY", :zh, :en]}

所以在 Rails 应用程序启动和调用控制器的 set_locale 方法之间的某处,I18n.fallbacks 正在重置为默认值。

别问我为什么,不管官方文档怎么说,这都行得通。

require File.expand_path('../boot', __FILE__)

require 'rails/all'
require "i18n/backend/fallbacks"

Bundler.require(*Rails.groups)

module MyAwesomeApp
  class Application < Rails::Application
    # all translations from config/locales/**/*.rb,yml are auto loaded.
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

    # The default locale is :en
    config.i18n.default_locale = :en

    # See http://guides.rubyonrails.org/i18n.html#localized-views for a
    # mostly correct discussion of how language codes fall-back.
    config.i18n.available_locales = [:en, :'zh-CN', :'zh-TW', :'en-SG', :'en-MY', :'zh-MY']
    config.i18n.fallbacks = {:'zh-MY' => :'zh-CN'}
  end
end

删除 I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks) 并通过 config.i18n.fallbacks = {:'zh-MY' => :'zh-CN'} 而不是 I18n.fallbacks.map(:'zh-MY' => :'zh-CN') 设置回退,这一切都将完美运行。

现在在我的控制器中,在第三个问题更新中讨论的相同断点处:

[1] pry(#<ServicesController>)> I18n.fallbacks
=> {:en=>[:en], :"zh-MY"=>[:"zh-MY", :zh, :"zh-CN", :en]}

希望对其他人有所帮助。