From: Robert Klemme Date: 2005-04-15T20:34:36+09:00 Subject: Re: class locals as class methods "Trans" schrieb im Newsbeitrag news:1113499156.837299.173260@z14g2000cwz.googlegroups.com... > So I find myself once again creating some classes that have > attributes/state. I have two options, either the class defines > a class method for the info, or in a superclass I define a method > that will set that info to a class var when called. > > # Example A > class Thing1 < TheseThings > def self.mystate ; "what have you" ; end > end > > or > > # Example B > class Thing1 < TheseThings > mystate "what have you" > end > > The first is rather, well, ugly. Although it makes sense, it's > what one does at the instance level all the time (i.e. defining > methods to fit the interface). The second is nice and dsl-ish, > but requires a method to be predefined in TheseThings which > actually creates a number of oddities, like how does one read > the info out, and still be able to set it to nil? If that's an > issue one is lead to instead define two class methods, and > having to use self.maystate = "blah blah", instead. > > Now everytime I go about this kind of thing I actually find > myself writing: > > # Example C > class Thing1 < TheseThings > mystate = "what have you" > end > > as that just feels natural. But then I have to go back and fix > it, of course. So last night it hits me, why not? Why not have > class locals define class methods? So in this case, Example C > would basically be like doing Example A. Yes, I know there's > namespace overlap, but class locals are rare enough that I don't > think that's a show stopper. Maybe there are other problems I'm > not seeing, perhaps there's some OOP formalism that this rubs the > wrong way. I don't know. But I've given it more than "15 minutes" > and it's actually growing on me. Am I crazy? Probably - but then again, aren't we all? :-) Ok, here's what I'd probably do: class TheseThings module ThingClassProperties attr_accessor :mystate # needed for further inheritance levels def inherited(cl) cl.extend ThingClassProperties end end extend ThingClassProperties end class Thing1 < TheseThings self.mystate = "t1 state" end class Thing2 < Thing1 self.mystate = "t2 state" end p Thing1.mystate p Thing2.mystate 13:28:13 [source]: ruby /c/temp/ruby/meta-prog.rb "t1 state" "t2 state" You can make that even smarter by defining property accessors on the fly etc. Cheers robert