From: Alder Green Date: 2006-06-08T17:02:35+09:00 Subject: Re: Why the lack of mixing-in support for Class methods? On 6/8/06, Phil Tomson wrote: > On 6/7/06, Alder Green wrote: > > Hi > > > > I'm confused as to why class methods aren't include'd by default along > > with instance methods when mixing-in modules. > > > > It obstructs the important orthoganility between modules and classes, > > and - among other problems - thus undermines the position of mixins as > > an alternative to class-based multiple inheritance. > > > > In short, I can see a lot of poor consequence to that lack of support, > > while on the other hand no good reason for it. Maybe someone would > > care to elighten me? > > > > (I'm aware of the various hacks for fudging such support, and in fact > > use some of them in my code. But there are readability and > > maintainability issues with those hacks for something that's supposed > > to be a core feature). > > > > The main reason is because a different 'self' is involved, I would guess. > You can use extend to mixin class methods. Also, there's a nice idiom > for getting include to mixin both class and instance methods of a > module (though the class methods are actually in another sub-module): > > module A > def self.included receiver > receiver.extend ClassMethods > end > > module ClassMethods > def foo > "foo" > end > end > def inst_method > "instance method" > end > end > > class B > include A > end > > B.foo #=> "foo" > B.new.inst_method #=> "instance method" > > Yes, I'm using this idiom in my code. Note, however, that if you want to use A'd "class methods" from A itself, you have to add the extra line: self.extend(ClassMethods) after A::ClassMethods's definition. Still, it's unclear to me why this very natural functionality isn't built into the default append_features. It hinders the ease of going from a module to a class or vice-versa, which Ruby seems to encourage. In any case, every other aspect of switching between those two is well-handled, so why not this one as well? Are there plans to add it for Ruby 2? -- -Alder