From: Lionel Thiry Date: 2005-04-15T06:24:39+09:00 Subject: Re: class locals as class methods Trans a �crit : > 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 > You can use the attr_* instead: class Thing1 < TheseThings class < 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. That's actually how python works. class Thing1(TheseThings): my_state = "what have you" print Thing1.my_state # output: what have you Well, it doesn't really create a my_state method, and doesn't really create some @my_state anywhere. But at use, it works the same as you'd want ruby to work. > 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 haven't the ability to demonstrate you anything, but my intuition is that it is not much adequate for ruby... > I don't know. But I've given it more than "15 minutes" > and it's actually growing on me. Am I crazy? Crazy of wanting ruby to look like python? Err... ;) -- Lionel Thiry