Rails edge revision 8056 introduces some great new reader/writer/accessor methods:
- superclass_delegating_reader
- superclass_delegating_writer
- superclass_delegating_accessor
This is best explained with an example:
class Foo
superclass_delegating_accessor :name
end
class Bar < Foo ; end
class Baz < Foo ; end
Foo.name = "Mr. T" # => "Mr. T"
Foo.name # => "Mr. T"
Bar.name # => "Mr. T"
Baz.name # => "Mr. T"
Bar.name = "Junkyard Dawg" # => "Junkyard Dawg"
Foo.name # => "Mr. T"
Bar.name # => "Junkyard Dawg"
Baz.name # => "Mr. T"
Foo.name = "Million $$ Man" # => "Million $$ Man"
Foo.name # => "Million $$ Man"
Bar.name # => "Junkyard Dawg"
Baz.name # => "Million $$ Man"
There are two reasons why this rocks:
-
you can independently override something on a subclass without screwing up the the value for the inheritance hierarchy (which is the problem with cattr_accessor/reader/writer methods).
-
you can update the superclass’s value and the subclasses which don’t set their specify their own value will receive the update (which is the problem with class_inheritable_accessor/reader/writer methods).
blog comments powered by Disqus