Overriding Default Error Messages, New Styley!

Aug 21st, 2008 — 3:50 PM

I’m posting this for anyone who’s googling how to replace their old school error message overrides with the new Rails’ I18n-compatible version.

Old school [please note this is the old, deprecated way just shown here for google to hook into for people searching on various lines of the old code]:

module ActiveRecord
  class Errors
    @@default_error_messages.merge!({
      :invalid => "doesn't appear to be valid",
      :too_long => "can't be more than %d characters",
      :too_short => "can't be less than %d characters",
      :wrong_length => "must be exactly %d characters",
      :taken => "is already taken",
    })
  end
end

New school [updated to latest edge Rails]:

I18n.backend.store_translations "en-US", {
  :activerecord => {
    :errors => {
      :messages => {
        :invalid => "doesn't appear to be valid",
        :too_long => "can't be more than {{count}} characters",
        :too_short => "can't be less than {{count}} characters",
        :wrong_length => "must be exactly {{count}} characters",
        :taken => "is already taken" 
      }
    }
  }
}

Filed under: rails

2 comments

  • Sven Fuchs said
    Hey Russell, actually the new-school-way is to use an explicitly named variable instead of the ruby interpolation syntax for the messages. So that would be "can't be more than {{count}} characters" instead of "can't be more than %d characters" %d still works but will be deprectated. The reason for this is that for translations with more than one value being interpolated to a translation (like "Hi {{name}}, you have {{count}} messages.") the order of the variables might change depending on the language. It's not always possible to find reasonable translations with the same variable order for all languages. Also, this gives us the opportunity to send more interesting stuff to the interpolation. IIRC current edge adds the model and attribute names for all messages as well as another value for special methods. Would have to look at the code though :)
  • RSL said
    Oops. I thought I'd actually fixed this in the post this weekend. I noticed the new deprecation warnings and updated but it looks like the cache sweeper is borked ATM [which is why your comment didn't show up as well]. Fixed now. Thanks! That new interpolation method in your example really, really cool. Opens up a lot of interesting possibilities even if you're not using internationalization. Great job, man!

Leave a Comment

Lucky Sneaks is designed and managed by Lucky Sneaks
All content © Lucky Sneaks 2008
Lucky Sneaks is Lucky Sneaks