cattr_accessor in Rails? cattr_accessor in Rails? ruby-on-rails ruby-on-rails

cattr_accessor in Rails?


It is a rails thing. Basically like the attr_* methods, but for the class level. One thing you wouldn't expect is because it uses a backing @@ variable, the value shared between the class and all instances.

class Foo  cattr_accessor :barend# => [:bar] foo1 = Foo.new# => #<Foo:0x4874d90> foo2 = Foo.new# => #<Foo:0x4871d48> foo1.bar = 'set from instance'# => "set from instance" foo2.bar# => "set from instance" Foo.bar# => "set from instance" 


For those that stumble across this question too, there is a new way to do this in Rails 3 that works for subclasses:

class_attribute :name

A good blog post on it here.


Defines both class and instance accessors for class attributes

class Person  cattr_accessor :hair_colorsendPerson.hair_colors = [:brown, :black, :blonde, :red]Person.hair_colors     # => [:brown, :black, :blonde, :red]Person.new.hair_colors # => [:brown, :black, :blonde, :red]

If a subclass changes the value then that would also change the value for parent class. Similarly if parent class changes the value then that would change the value of subclasses too.

class Male < PersonendMale.hair_colors << :bluePerson.hair_colors # => [:brown, :black, :blonde, :red, :blue]

but for Rails 4+ use similar method mattr_accessor, as cattr_accessor is deprecated in rails 4