Rails I18n translate with empty string - bug?
Normally, it's pretty easy in Rails to take advantage of the simple i18n tools provided. You just write I18n.t("some_key") and it'll translate that into whichever language.
Today, however, I discovered what seems like a problem. If you do I18n.t(""), it returns a hash of all possible translations! And if you give it a nil, it returns an error because that's not a key in the DB.
The first behavior doesn't sound correct at all, and the second seems dubious as well. I'm thinking about fixing it like so:
def translate(key, options = {})
return nil if key.nil?
return "" if key == ""
locale = options.delete(:locale) || I18n.locale
backend.translate(locale, key, options)
rescue I18n::ArgumentError => e
raise e if options[:raise]
send(@@exception_handler, e, locale, key, options)
end
Is there any reason not to do this?
Trackbacks
Use the following link to trackback from your own site:
http://journal.dedasys.com/trackbacks?article_id=2195
about 2 hours later:
Don't translate "" that way. Almost any platform will have unexpected behaviour when you translate such strings. This is not just a Rails issue.
about 2 hours later:
Bob, the problem is that if you want to translate a string that may or may not be empty, you either have to put a tedious "if" in there each and every time.
about 3 hours later:
In the C or Python use of the gettext library, you get a (user-wise) useless gettext header back if you translate ""; any translation of "" is thus a bug there (and it's usually easy to spot). Of course it's a dubious design decision to make it this way.
about 3 hours later:
ulrik:
3 days later:
I was quite pissed at the move of making l18n the main Rails localization library... It might be more convenient in many ways for simple, short translations, but it is quite inferior to Gettext. Anyway, I'm still using Gettext (and recently finished packaging it for Debian).