Rails 3.0′s ActiveModel: How To Give Ruby Classes Some ActiveRecord Magic
One of the biggest benefits of bringing Merb developer Yehuda Katz on board to work on Rails 3.0 has been his relentless pursuit of extracting out all of Rails' magical abilities from their monolithic encasings and into separate, manageable chunks. A case in point is ActiveModel, a new library that provides the model related parts of ActiveRecord but without the database requirements.
Get Rails-like Model Behavior on Any Ruby Class
In extracting the model-building parts of ActiveRecord, ActiveModel makes it possible to add model-like behavior to any Ruby class, with no Rails or databases required. In his latest blog post, ActiveModel: Make Any Ruby Object Feel Like ActiveRecord, Yehuda shows off how to get Rails-style models with validations, serialization, callbacks, dirty tracking, internationalization, attributes, observers and all the other Rails goodness.
I've taken Yehuda's main example of using ActiveModel on a non Rails class and extended it with some code that actually uses the model:
require 'active_model' class Person include ActiveModel::Validations validates_presence_of :first_name, :last_name attr_accessor :first_name, :last_name def initialize(first_name, last_name) @first_name, @last_name = first_name, last_name end end a = Person.new("Fred", nil) a.valid? # => false a.last_name = "Flintstone" a.valid? # => true
If you're interested in ActiveModel and not so much in Rails 3.0, installing it is reasonably easy (though not as easy as only installing a gem just as yet):
- Go to or make a temporary directory
git clone git://github.com/rails/rails.git
gem install activesupport/pkg/activesupport-3.0.pre.gem
gem install activemodel/pkg/activemodel-3.0.pre.gem
Once this is all done, the code example above will work.
As an aside, if you fancy having a go with the full pre-release (a.k.a. "pre") version of Rails 3.0, check out Dr Nic's slightly out of date but otherwise useful guide.