Futzing around with Ruby, other languages, and further occasional idiosyncrasies.

Thursday, October 15, 2009

Rails i18n truly default locales

The now built-in i18n functionality in Rails is a great and simple way of internationalizing a Rails app. However, one annoying out-of-the-box feature is that if one of your locales is missing a translation string, it will default it to a message like "translation missing: es, whassup", so you have to make sure that every string on every locale is set, which can be a pain.

A gentler approach would be to fallback to a "default" locale, and look up the string there. Not to be confused with the I18n.default_locale which is the locale to use when no locale at all is specified by the request.

Luckily the designers left us a backdoor to deal with this in the form of the exception_handler. To setup the fallback functionality have this code run somewhere (an initializer perhaps):

require 'i18n'
module I18n  # Reopen library module
  def self.fallback_default_exception_handler(exception, locale, key, options)
    # Recursive case should fall through
    if exception.kind_of?(MissingTranslationData) && locale != self.default_locale
      begin
        return translate(key, options.merge(:locale => self.default_locale, :raise => true))
          # Always raise so we can catch it
      rescue MissingTranslationData
        # Fall through and handle as below
      end
    end
    send :default_exception_handler, exception, locale, key, options
  end
end

I18n.exception_handler = :fallback_default_exception_handler

0 comments:

Post a Comment