2

I would like to use I18n.t in an initializer file in Rails 3.1.1.

This question already exists for Rails 2 (http://stackoverflow.com/questions/3514536/unable-to-use-i18n-t-call-in-an-initializer-file). Supposedly, it was answered by a subsequent release. It appears to be an issue again in Rails 3.1.1.

The problem:

I have a custom time format called :dxl. I would like to format my Email.sent_at datetime as :dxl.

The solution:

In can add the format to en.yml (time.formats.dxl) and use it with:

I18n.localize(email.sent_at, :format => :dxl)

I also want to show the utc time. I do not see a way to use I18n for this, so I am using:

email.sent_at.utc.to_s(:dxl)

The rub:

To support to_s(format), I believe I need to assign Time::DATE_FORMATS[:dxl] in an initializer (e.g. config/initializers/time_formats.rb).

I would rather not duplicate the strftime format string in both en.yml and the initializer.

Unfortunately, it looks like I18n is not usable within an initializer. When I add this to config/initializers/time_formats.rb:

Time::DATE_FORMATS[:dxl] = I18n.translate('time.formats.dxl')

I get:

> Time.now.utc.to_s(:dxl)
=> "translation missing: en.time.formats.dxl"

Is there a way to ensure I18n is ready (has read the en.yml file) in an initializer?

I did verify that the translation does work correctly if I copy/paste the strftime format into the initializer.

Thanks.

Matt Scilipoti
  • 1,091
  • 2
  • 11
  • 15
  • Any reason why you're not just calling I18n.localize(email.sent_at.utc, :format => :dxl) ? – tigrish May 16 '12 at 08:44
  • I believe this how we settled on formatting dates. This is a little fuzzy for me now, but I do remember that, at the time, we were trying to use .to_s(format) instead of the bulkier I18n.translate. I also recall that the use of the optional param on to_s caused us some other issues, so we fell back to I18n.translate. – Matt Scilipoti May 21 '12 at 18:15

0 Answers0