如何检索所有的翻译从阳明海运文件的在轨I18n
-
26-09-2019 - |
题
我猜轨道的商店所有的分析翻译阳明海运文件,在一种阵/hash.有没有办法访问这个?
例如,如果我有一个文件:
en:
test_string: "testing this"
warning: "This is just an example
我可以做的东西一样,I18n.translations_store[:en][:test_string]?我可以分析阳明海运的文件与其::负荷,但在我的情况下,我们分裂的阳明海运文件,在文件夹,用于组织,而且我相当肯定,铁轨已经解析他们所有。
解决方案
您一定要呼吁后端的私有方法。这是你如何可以访问:
translations = I18n.backend.send(:translations)
translations[:en][:test_string] # => "testing this"
其他提示
作为每8xx8的评论,的简化版本:
I18n.t(:foo)
I18n.backend.send(:translations)[:en][:test_string]
是
I18n.t(".")[:test_string]
此减轻具有到两个预加载的翻译或指定的区域设置。
如果您正在使用I18n::Fallbacks
不幸,因为它刚刚从任意回退语言环境的返回内容的当前区域(如“EN-GB”)并没有什么,你不能使用I18n.t('.')
(如“恩”)。为了避开这个你可以遍历回退和使用deep_merge!
把它们结合起来。
module I18n
class << self
def all
fallbacks[I18n.locale].reverse.reduce({}) do |translations, fallback|
translations.deep_merge!(backend.translate(fallback, '.'))
end
end
end
end
默认I18n后台是I18n::Backend::简单,它不会获得翻译给你。(I18.后台。翻译是一个受保护的方法。)
这不是一个好主意,但是如果你真的需要这个信息并不能解析的文件,可以延长的后台类。
class I18n::Backend::Simple
def translations_store
translations
end
end
然后你可以叫 I18n.backend.translations_store
得到的分析翻译。你可能不应该依靠这一个长期的战略,但它得到你的信息你现在需要的。
如果你在一个rake任务这样做,记得要包括环境,否则就无法加载自己的语言环境这下config/locales/
生活
require "./config/environment.rb" # Do not forget this
namespace :i18n do
desc "Import I18n to I18n_active_record"
task :setup do
I18n.t(:foo)
translations = I18n.backend.send(:translations)
end
end
有关的人游荡到这个老问题,有可能不需要调用保护方法的解决方案。更改您的yml
文件如下:
nl: &all
... translations here ...
all:
<<: *all
现在你可以简单地使用提取I18n.t("all")
,其中有自动初始化和发展模式重装翻译的利益所有的翻译(的东西,如果你所说的保护方法,这不会发生。)
不隶属于 StackOverflow