> Is it possible to add class attributes (cattr_accessor) using a module?
> If so could you give an example?

There is no "Ruby Way" to do this b/c Ruby's module methods aren't
inherited by classes that include them. Though I've asked for a way
man times now!

It might seem easy to glaze by this, thinking nothing of
cattr_accessor, a seemingly esoteric method since it's not included in
core Ruby, but you will find it in both Rail's Active Support and Ruby
Facets. And in fact, you've brought up a nice example of how this play
out b/c cattr_accessor and it's ilk really don't do anything very
esoteric under the hood. I'm going to layout what cattr_accessor
essentially does* so all can see this for what it is and what happens
when you try to REUSE structures of this nature.

For a class, it is simply:

  class C
    def self.m ; @m ; end
    def self.m=(x) ; @m=x ; end
    def m ; self.class.m ; end
    def m=(x) ; self.class.m=x ; end
  end

Hence

  C.m = 10
  C.m  #=> 10
  c = C.new
  c.m  #=> 10
  c.m = 20
  c.m  #=> 20
  C.m  #=> 20

While you can subclass C with this functionality readily, eg 'class N
< C' works as you'd expect, try MODULARIZING this functionality. The
cooresponding

  module M
    def self.m ; @m ; end
    def self.m=(x) ; @m=x ; end
    def m ; self.class.m ; end
    def m=(x) ; self.class.m=x ; end
  end

does not work at all. You can't include it in a class, you can't
extend a class with it, nor both --it completely bombs. Feel free to
maniputlate the code as well --shame as that is, while you can get
closer, nothing completely works --there's alwasy something wrong.
Only ugly meta-programming hacks will give the sought behavior --and
even then their are corner-case complications.

T.


* I'm using an instance var in this case rather than a class var for
simplicity sake, but it makes no difference to the problem itself.