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.
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.
Example CodeI'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
Installing ActiveModel
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.gitcd railsrake gemgem install activesupport/pkg/activesupport-3.0.pre.gemgem 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.