Flowdock

Notes posted by jesseclark

RSS feed
August 19, 2009 - (v2.1.0 - v2.3.2)
0 thanks

Gotcha with class_inheritable_accessor and cloneing the attribute values

The key thing to note from post is that class_inheritable_accessor copies the value from the parent class at inherit time. So, if you are setting a default value of an array and doing something like the following you might end up with unintended results:

>> A.class_inheritable_foo << 'from a'
=> ["from a"]
>> B.class_inheritable_foo << 'from b'
=> ["from a", "from b"]
>> C.class_inheritable_foo << 'from c'
=> ["from a", "from b", "from c"]

However, if you use the form:

class << self
  def class_instance_foo
    @class_instance_processors ||= []
  end
end

The original values aren’t copied from the parent class when you reference the class for the first time:

>> A.class_instance_foo << 'from a'
=> ["from a"]
>> B.class_instance_foo << 'from b'
=> ["from b"]
>> C.class_instance_foo << 'from c'
=> ["from c"]