ruby-on-rails - 带 rails 的奇怪的I18n日期输出

标签 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

这并非特定于特定的 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/

相关文章:

vba - 使用 vba 将 ddmmmyyyy 转换为数字

php - 将日期时间插入数据库 PHP

ruby-on-rails - 从父应用程序重新打开 Rails 3 引擎类

sql - Rails 4 清理用户输入

ruby-on-rails-3 - 如何在我的 gemfile 中获取公共(public) git repo 的最新提交?

ruby-on-rails - Ruby on Rails错误 rake db :migrate

ruby-on-rails - rails : Prevent duplicate inserts due to pressing back button and save again

mysql - 导入时主键如何从0开始

mysql - Rails 表单未写入数据库

java - 使用Java获取月份中两个日期之间的差异