From: Trans Date: 2005-04-17T01:14:38+09:00 Subject: Re: self Robert Klemme wrote: > Oooops... :-))) > > Looks like it's rather me that has to go back to school. Now *you* explain > why it works. Oh dear. Why? Uh.....It just do! > >> Here's what I do if I want to have a set of singleton methods > > available for > >> all classes in a class hierarchy: > >> > >> class Base > >> module MySpecialClassMethods > >> # make inheritance work: > >> def inherited(cl) cl.extend MySpecialClassMethods end > >> > >> attr_accessor :bar > >> def foo() "foo" end > >> # other methods... > >> end > >> > >> extend MySpecialClassMethods > >> end > > > > You're right, this is a great approach. > > But apparently superfluous > > >> class My2 < MyClass > >> do_something > >> end > success > => nil > > Could it be that this didn't work in older versions? I'm almost sure that I > did try this once and it failed. This is strange... Actually I think it always has. But what doesn't is this: module MyNotSoSuperModule def self.do_something puts "success" end end class MyClass include MyNotSoSuperModule do_something end #=> undefined local variable or method `do_something' for MyClass:Class (NameError) Maybe you got the cases crossed? Actually I got them crossed myself, as I was thinking your example did us this service by allowing modules to include class-level methods, but that would actually require using #included rather then #inherited, like this: module Base module MySpecialClassMethods # make inheritance work: def included(cl) cl.extend MySpecialClassMethods p self, cl end attr_accessor :bar def foo() "foo" end # other methods... end extend MySpecialClassMethods end class Derived include Base end p Derived.foo class Derived2 < Derived end p Derived2.foo And that is a good idea, I think. > Thanks for crushing my certainty! Hey, no problem. I'm an expert at crushing my own, so the least I could do was share :-) T.