views:

145

answers:

2

When classes are inherited in Ruby the singleton classes are also inherited:

class A
  def self.hello
    puts "hello"
  end
end

class B < A
end

B.hello #=> "hello"

Yet with modules, this is not the case:

module M
  def self.goodbye
    puts "goodbye"
  end
end

class A
  include M
end

A.goodbye #=> NameError

To get around this limitation many ppl resort to this ugly hack:

module M
  def self.included(c)
    c.extend ClassMethods
  end

  module ClassMethods
    def goodbye
      puts "goodbye"
    end
  end
end

Ok, so my question: is there a theoretical/conceptual reason behind this limitation on modules? or was it just an implementation difficulty?

After looking at the C source code (YARV/MRI) I can identify there is an implementation difficulty (not insurmountable, but one all the same), but is this the sole reason? Are there any other reasons for this limitation?

thanks

A: 

Warning: the following is just speculation.

If you're using a class, you'll need singleton class methods, because you rely on them to create the object (eg MyClass.new). If you're using a module, you don't need them, because you can't create objects purely from a module.

Andrew Grimm
singleton methods can be used for much more than creating objects; i dont think this can be the reason, but thanks:)
banister
+1  A: 

Unless anyone can come up with a compelling argument, i feel that the limitation is just down to implementation difficulty. Nonetheless i've been working on the problem the last couple of days and have (in beta) a new version of include called real_include that gets around these difficulties and allows modules inheritance to work like class inheritance (bringing in the singleton)

Check out the project here: http://github.com/banister/real_include

And beware the project is still very much in beta, but still seems to work as desired so far

banister