The test:
def test_cannot_change_country_name_once_constructed country = Country.new(:name => 'UK') assert_raise RuntimeError do country.name = 'USA' endend
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 endend