在另一个模块中扩展Ruby模块,包括模块方法 [英] Extending a Ruby module in another module, including the module methods
本文介绍了在另一个模块中扩展Ruby模块,包括模块方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每当我尝试扩展ruby模块时,都会丢失模块方法.包含或扩展都不会这样做.考虑一下代码段:
Whenever I try to extend a ruby module, I lose the module methods. Neither include nor extend will do this. Consider the snippet:
module A
def self.say_hi
puts "hi"
end
end
module B
include A
end
B.say_hi #undefined_method
无论B包含还是扩展A,都不会定义say_hi.
Whether B Includes or Extends A, say_hi will not be defined.
有什么办法可以完成这样的事情吗?
Is there any way to accomplish something like this?
推荐答案
如果您是module A
的作者,并且经常需要这样做,则可以像这样重新编写A:
If you are the author of module A
and will frequently need this, you can re-author A like so:
module A
module ClassMethods
def say_hi
puts "hi"
end
end
extend ClassMethods
def self.included( other )
other.extend( ClassMethods )
end
end
module B
include A
end
A.say_hi #=> "hi"
B.say_hi #=> "hi"
这篇关于在另一个模块中扩展Ruby模块,包括模块方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文