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.