Archive for

September 2007

The Fantastically Honest RDoc

Whilst working on a bit of code the other day we found this little nugget in the RDoc for Object#instance_variable_set:

Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class‘s author to attempt to provide proper encapsulation.

Brilliant!

Posted

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'  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

Posted
Fork me on GitHub