在另一个模块中扩展 Ruby 模块,包括模块方法 [英] Extending a Ruby module in another module, including the module methods
本文介绍了在另一个模块中扩展 Ruby 模块,包括模块方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每当我尝试扩展 ruby 模块时,我都会丢失模块方法.include 和 extend 都不会这样做.考虑片段:
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屋!
查看全文