In Ruby on Rails 3, non-database functionality was moved from ActiveRecord to ActiveModel. This is great since it makes it easy to use all the ActiveRecord niceness we’ve come to love for non-ActiveRecord models.
My favorite bit of functionality moved to ActiveModel is localization. (Well, validations are actually my favorite, but localization is a close second.) Rails has robust localization support though the Rails Internationalization (I18n) API. Hopefully you’re already using it, if not for creating multi-lingual sites, then at least for keeping custom attribute and model names consistent between labels, errors messages, etc.
The Rails guide does a great job of walking us through the basics of localization and using it with an ActiveRecord object, but falls short when looking at ActiveModel localization. So let’s dive in…
Let’s say we have the following namespaced model:
attr_accessor :name, :price, :image_url
As you can see, we’ve already included some ActiveModel modules. Conversion gives us useful methods including to_param and to_key. AttributeMethods gives us lots of accessor and attribute related goodness. And Validations gives us, well, validations.
Let's look at the attributes. The "name" and "price" attributes will humanize nicely to "Name" and "Price" but I want to refer to "image_url" as "Puppy Pic", not the default humanization "Image Url". This looks like a job for localization!