开发者

Why does Ruby module inclusion exclude the module's singleton class?

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
  开发者_如何学JAVAdef 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


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 include_complete 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/include_complete

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜