Friday, May 28, 2010

Tweaking on Rails 3.0: #3 class_attribute


We all know that class variables in Ruby don't work well with inheritance. For this reason, ActiveSupport originally added class_inheritable_accessor (view source). The method works by using the Class.inherited callback, and copying attributes down to subclasses. This was basically a hack. It failed to work correctly if the parent's accessor was written to after the inherited classes were defined, and it's wasteful to copy attributes to every inheriting class.

Along comes class_attribute (view source). It works by defining the class accessor methods on the class's singleton class. The technique is described in more detail by a railstips.org article. The win is that we're getting true inheritance and expected behavior.

How do you improve your code in Rails 3? Simply replace the text class_inheritable_accessor with class_attribute!

No comments: