Ruby 的 include 的反面是什么? [英] What is the opposite of Ruby's include?
问题描述
如果我有一个包含多个包含模块的类实例,我是否可以动态取消包含特定模块(为了替换它)?
If I have a class instance, containing several included modules, can I dynamically un-include a specific module (In order to replace it)?
谢谢.
推荐答案
它真的不是一回事,但你可以用这样的东西来伪造它:
It's not really the same thing, but you can fake it with something like this:
module A
def hello
puts "hi!"
end
end
class B
include A
end
class C
include A
end
B.new.hello # prints "Hi!"
class Module
def uninclude(mod)
mod.instance_methods.each do |method|
undef_method(method)
end
end
end
class B
uninclude A
end
B.new.hello rescue puts "Undefined!" # prints "Undefined!"
C.new.hello # prints "Hi!"
这在普通情况下可能有效,但在更复杂的情况下它会咬你,比如模块将自身插入继承链,或者你有其他模块提供了你仍然希望能够命名的相同内容的方法打电话.您还需要手动反转 Module.included?(klass)
所做的任何事情.
This may work in the common case, but it can bite you in more complicated cases, like where the module inserts itself into the inheritance chain, or you have other modules providing methods named the same thing that you still want to be able to call. You'd also need to manually reverse anything that Module.included?(klass)
does.
这篇关于Ruby 的 include 的反面是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!