Search
Me

Developer for Forward. Former Technical Lead at ThoughtWorks.

Recent Comments
Elsewhere
« The Fantastically Honest RDoc | Main | The joys of a wide-angle lens »
Monday
10Sep2007

Immutable ActiveRecord Attributes

The test:

def test_cannot_change_country_name_once_constructed
country = Country.new(:name => 'UK')
assert_raise RuntimeError do
country.name = 'USA'
end
end

The class:

class Country < ActiveRecord::Base
extend ImmutableModel
immutable :name
...

The implementation:

module ImmutableModel
def immutable(attr_name)
define_method "#{attr_name}=" do |new_value|
read_attribute(attr_name).nil? ? write_attribute(attr_name, new_value) : raise(RuntimeError, "You can't change #{attr_name} once it has been set")
end
end
end

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>