我在Ruby On Rails 3应用程序中的日期翻译遇到了一个奇怪的问题,我真的不明白为什么...
这是我的en.yml
和fr.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
这并非特定于特定的 View ,例如在我的一个 View 中:
<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相关的所有东西都可以正常工作,但日期除外。
谢谢你的帮助 !
最佳答案
我想我终于想通了,很抱歉花了这么长时间。
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
用于日期/时间的“字符串”部分,而是尝试自行完成。添加上述月份和日期名称的翻译(作为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#[]
,最终您会得到随机查找的单个字符的月份和日期名称。
关于ruby-on-rails - 带 rails 的奇怪的I18n日期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12664062/