带轨道的奇怪的I18n日期输出

时间:2012-09-30 18:57:02

标签: ruby-on-rails ruby-on-rails-3 date localization internationalization

我的Ruby On Rails 3应用程序中的日期翻译有一个奇怪的问题,我真的不明白为什么......

以下是我的en.ymlfr.yml

fr:
  date:
    formats:
      default: "%d/%m/%Y"
      short: "%e %b"
      long: "%e %B %Y" 
  time:
    formats:
      default: "%d %B %Y %H:%M:%S"
      short: "%d %b %H:%M"
      long: "%A %d %B %Y %H:%M"
    am: 'am'
    pm: 'pm'



en:
  date:
    formats:
      default: "%Y-%m-%d"
      long: "%B %d, %Y"
      short: "%b %d"
  time:
    am: am
    formats:
      default: ! '%a, %d %b %Y %H:%M:%S %z'
      long: ! '%B %d, %Y %H:%M'
      short: ! '%d %b %H:%M'
    pm: pm

这不是特定于某个特定视图,而是在我的一个视图中:

<td><%=l job_application.created_at, :format => :default %></td>

我得到那些奇怪的输出:

With locale = :en
=> t, 30 o 2012 18:09:33 +0000

With locale = :fr
=> 30 o 2012 18:09:33

这些错误的“格式”来自哪里?

我正在使用Rails 3.2.8(使用Postgresql / gem pg),与I18n相关的所有内容都可以正常工作,除了日期

感谢您的帮助!

3 个答案:

答案 0 :(得分:11)

我想我终于想出来了,抱歉这么久。

Rails l帮助程序只调用I18n.localize。如果您追踪I18n.localize代码,那么您最终会here

format = format.to_s.gsub(/%[aAbBp]/) do |match|
  case match
  when '%a' then I18n.t(:"date.abbr_day_names",                  :locale => locale, :format => format)[object.wday]
  when '%A' then I18n.t(:"date.day_names",                       :locale => locale, :format => format)[object.wday]
  when '%b' then I18n.t(:"date.abbr_month_names",                :locale => locale, :format => format)[object.mon]
  when '%B' then I18n.t(:"date.month_names",                     :locale => locale, :format => format)[object.mon]
  when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format) if object.respond_to? :hour
  end
end

因此,localize助手不会将strftime用于&#34; stringy&#34;日期/时间的一部分,它试图自己做。如上所述,为月份和日期名称添加翻译(作为YAML中的数组),您的本地化日期和时间应该开始有效。

如果你的YAML中没有这些翻译数组,那么I18n.t(:"date.abbr_month_names")会给你这样的字符串:

"translation missing: en.date.abbr_month_names"

然后I18n.localize最终会做出如此愚蠢的事情:

"translation missing: en.date.abbr_month_names"[10]

这将使用String#[]而不是预期的Array#[],您最终会看到随机查找单个字符的月份和日期名称。

答案 1 :(得分:1)

  

这些错误的“格式”来自哪里?

由于created_at是日期时间,因此使用time格式(不是date)进行导航。

https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml#L195

time:
  am: am
  formats:
    default: ! '%a, %d %b %Y %H:%M:%S %z'

答案 2 :(得分:0)

输入控制台

I18n.t(:"date") 

检查是否获得在翻译.yml文件中定义的翻译。

将结构与标准的EN语言环境进行比较

I18n.t(:"date", locale:'en')

这使我注意到我在date:中两次声明了.yml属性,而第一部分被第二个声明覆盖。

您应该获得在致电

时声明的abbr_month_names
I18n.t(:"date.abbr_month_names")

这些是调用%b时将使用的那些。

如果没有,请检查您的区域设置.yml文件,以确保正确声明了它们,并且没有两次声明。

您还可以调用I18n.locale来检查您正在编辑的.yml文件是否是rails正在使用的文件