Monday
10Sep2007
Immutable ActiveRecord Attributes
Monday, September 10, 2007 at 08:21PM The test:
def test_cannot_change_country_name_once_constructed
country = Country.new(:name => 'UK')
assert_raise RuntimeError do
country.name = 'USA'
end
endThe 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
Paul |
Post a Comment | tagged
rails activerecord
rails activerecord 


Reader Comments