views:

402

answers:

2

I can't work out from looking through the source what the difference is between the cattr_* and mattr_* methods provided in Class and Module respectively. I read this question: http://stackoverflow.com/questions/185573/what-is-mattr-accessor-in-a-rails-module which gives some details about both methods but doesn't highlight the differences.

So my question is what is the difference between them and why do we need both sets of methods when they are practically identical in the source? Also, which should we use when?

A: 

cattr_xxx works for class variables, and mattr_xxx works for module variables.

More here.

Dmytrii Nagirniak
But what's the difference between class and module variables - they are both just @@variable variables and since a Class is a Module you can call both cattr_* and mattr_* from inside a class. Are they then functionally equivalent? What happens in the case of inheritance and module inclusion - same in each case?
tobyclemson
+2  A: 

Module is the superclass of the class Class so if a suitably generic name could be thought of then the methods for defining accessors could be put on Module and it would work for modules and classes. Notice that the follow works:

class Bar
  mattr_accessor :test
end

but

module Foo
  cattr_accessor :test
end

wouldn't work.

Having a c prefix on the methods that should be used inside classes and an m prefix on the methods for use inside modules just helps to make your code a bit clearer.

mikej
So functionally they are completely equivalent? Also, this makes me wonder why they haven't been DRYed up in the Rails source as the method bodies are identical...
tobyclemson