Simply, cattr_accessor creates a class-level accessor for a class variable. It also adds an instance method for accessing the class variable. There are several options that can be specified to remove the instance_reader and instance_writer. Cattr_accessor is located in the file activesupport/lib/active_support/core_ext/class/attribute_accessors.rb.
These class variables are shared with any subclasses, so be carefull. For example -
Loading development environment (Rails 3.0.0.beta3)irb(main):001:0> class Pet irb(main):002:1> cattr_accessor :numberirb(main):003:1> end=> [:number]irb(main):004:0> class Dog <>irb(main):005:1> end=> nilirb(main):006:0> class Cat <>irb(main):007:1> end=> nilirb(main):008:0> Dog.class_eval('number = 4')=> 4irb(main):009:0> Cat.class_eval('number = 0')=> 0irb(main):010:0> puts Dog.class_eval('number')0=> nilirb(main):011:0>
This is because the inherited accessors all reference the Pet's number.
No comments:
Post a Comment