What is the difference between cattr_accessor and attr_accessor? First off, cattr_accessor is part of Ruby on Rails ActiveSupport and not a feature of the Ruby language like attr_accessor.
cattr_accessor is class level equivalent of attr_accessor and can be classified as a singleton method. So cattr_accessor operates at the class level, while attr_accessor operates at the instance level.
Here is an example using a Counter class:
class Counter cattr_accessor :class_count attr_accessor :instance_count end counter1 = Counter.new counter1.instance_count = 1 counter1.class_count = 1 counter2 = Counter.new p counter2.instance_count #> nil p counter2.class_count #> 1
As you can see the cattr_accessor stays the same for every instance, while the attr_accessor is only on the instance of the class.
Behind the scenes it is just using class and instance variables for the getter/setter methods.
@@class_count @instance_count




#1 by soundarapandian on June 14, 2011 - 7:38 am
Quote
Nice. Very useful
#2 by Loganathan on December 17, 2011 - 11:44 pm
Quote
Thanks lot for this post
#3 by Ilia on May 21, 2012 - 2:45 am
Quote
very understandable
#4 by Nitin Agarwal on November 5, 2012 - 2:09 am
Quote
Thanks for this small and precise explanation.