Ruby – cattr_accessor vs attr_accessor

What is the difference in these two. You see attr_accessor alot more than cattr_accessor. I actually just stumbled upon it while trying to understand the ActiveRecord code.

Apparently, cattr_accessor is class level equivalent of attr_accessor. 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

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.