Hi --

On Tue, 21 Feb 2006, Mark Volkmann wrote:

> On 2/21/06, Xavier Noria <fxn / hashref.com> wrote:
>> Is there standard idiom to add module methods to classes that mixin
>> them? (Heh, is "mixin" also a verb in Ruby?)
>>
>> That is, I would like class C to croak:
>>
>>    module M
>>      def self.croak
>>        puts "croak!"
>>      end
>>    end
>>
>>    class C
>>      include M
>>      croak
>>    end
>
> When you say you want class C to croak, I assume you really mean you'd
> like for objects from the class C to be able to croak. Remove the line
> "croak" from the class C definition and do this.
>
> c = C.new
> c.croak
>
> The rest of your code looks fine.

I don't think that's what Xavier wanted; I think he wanted C to be
able to call M.croak.  (Also, in your example, c doesn't respond to
croak.)

This is an often-discussed question.  Some common answers:

   1. module M; def croak; ....; end;  class C; extend M; end
   2. put "class methods" into M::ClassMethods, and then write
      an M#included hook that extends C with M::ClassMethods
      while also including the rest of M in C.
   3. don't do that, because if you want two modules, just write
      two modules in the first place and don't shoehorn "class
      methods" in as instance methods of an inner module
   4. ask Matz to make some fundamental change so that include M
      does what people call "what you expect" (which is not what
      I expect)

And probably more :-)  I would give gold, silver, and bronze to #1,
#3, and #2, in that order.


David

-- 
David A. Black (dblack / wobblini.net)
Ruby Power and Light (http://www.rubypowerandlight.com)

"Ruby for Rails" chapters now available
from Manning Early Access Program! http://www.manning.com/books/black