是否可以在yaml键中使用连字符以在我的I18n en.yml文件中使用?

时间:2015-05-12 13:08:35

标签: ruby-on-rails ruby yaml rails-i18n

例如:

en:
  foobar-does-not-work: 'This is my value'

然后,如果我这样做:

t(foobar-does-not-work) # => returns nil

这不会在Ruby的yml中解析。有没有办法使它工作?我的密钥基于其中包含短划线(-)的网址。

3 个答案:

答案 0 :(得分:5)

您使用的是哪个版本的红宝石?你能告诉我们你的代码和错误吗?

它对我有用:

> require 'yaml'
> YAML.load_file('foo.yml')
{"en"=>{"foobar-does-not-work"=>"This is my value"}} 

当我将它添加到我的en.yml中时它会起作用:

> I18n.t('foobar-does-not-work')
=> "This is my value" 

您检查过I18n.locale的值吗?

答案 1 :(得分:1)

我认为你在调用t方法时只是使用了错误的密钥。删除' en'从关键。它应该是:

t('foobar-does-not-work')

答案 2 :(得分:1)

显然,有一个潜在的问题需要解决。有一个很好的工具可以分析你的i18n YAML作为Rails应用程序,我发现它在调试中非常有用。

安装并运行此gem i18n-tasks:https://github.com/glebm/i18n-tasks

创建i18n组件的综合报告:

$ i18n-tasks health

从他们的规范:

This gem analyses code statically for key usages, such as I18n.t('some.key'), in order to:

Report keys that are missing or unused.
Pre-fill missing keys, optionally from Google Translate.
Remove unused keys.
Thus addressing the two main problems of i18n gem design:

Missing keys only blow up at runtime.
Keys no longer in use may accumulate and introduce overhead, without you knowing it.

我不确定gem是否打算用作i18n调试工具,但我发现它对于在i18n中难以找到问题进行调试很有用。