Tuesday, May 29, 2007

Hammering localized dates into Ruby's strftime

Ruby on Rails in not really built with internationalization in mind. So here is a quick and dirty monkey patch to hammer Japanese date locales into place. Add it to your environment.rb. Note the use of .replace instead of a simple =. This is to avoid Ruby's warning about reassigning an already initialized constant.

Date::ABBR_DAYNAMES.replace %w(日 月 火 水 木 金 土)
Date::DAYNAMES.replace %w(日曜日 月曜日 火曜日 水曜日 木曜日 金曜日 土曜日)
Date::ABBR_MONTHNAMES.replace %w(1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月)
Date::MONTHNAMES.replace %w(一月 二月 三月 四月 五月 六月 七月 八月 九月 十月 十一月 十二月)
class Time
alias :strftime_nolocale :strftime
def strftime(format)
format = format.dup
format.gsub!(/%a/, Date::ABBR_DAYNAMES[self.wday])
format.gsub!(/%A/, Date::DAYNAMES[self.wday])
format.gsub!(/%b/, Date::ABBR_MONTHNAMES[self.mon - 1])
format.gsub!(/%B/, Date::MONTHNAMES[self.mon - 1])
self.strftime_nolocale(format)
end
end

The original Japanese site this was based on is now 404, but for a more complete (true internationalization) solution involving gettext check this page. If localization is all you are after, the above should work just fine.

1 comment:

Yves-Eric said...

How To Define Your Own Date Format, another interesting resource on the RoR wiki site.

Not mentioned on that page: the default date/time formats are defined under the ":default" key.