如何反转ruby的include函数 [英] How can I reverse ruby's include function

查看:92
本文介绍了如何反转ruby的include函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将解释我在代码中寻找的代码,因为它可能是最简洁的:

 模块Mixin 
def method
putsFoo
end
end

类无论
包括Mixin
end
$ b bw = Whatever.new
w.method
=> Foo

#一些魔法在这里
w2 = Whatever.new
w.method
=> NoMethodError

我试过使用remove_const取消定义Mixin模块,但是这似乎没有做任何差异到什么。我假设#include只是将模块的引用添加到类的方法解析链中 - 但是这种行为与此不同。



任何人都可以告诉我什么

$

 模块Mod $  

b $ b def foo
putsfooing
end
end

类C
包括Mod
def self.remove_module(m)
m.instance_methods.each {| m | undef_method(m)}
end
end

>> c = C.new
>> c.foo
fooing
>> C.remove_module(Mod)
=> [foo]
>> c.foo
NoMethodError:undefined method`foo'for#< C:0x11b0d90>


I'll explain what i'm looking for in code as thats probably the most succinct:

module Mixin
  def method
    puts "Foo"
  end
end

class Whatever
  include Mixin
end

w = Whatever.new
w.method
=> "Foo"

# some magic here
w2 = Whatever.new
w.method
=> NoMethodError

I had tried just undefining the Mixin module using remove_const, but this doesn't seem to make any difference to Whatever. I had assumed that #include just added a reference to the module into the class's method resolution chain - but this behaviour doesn't agree with that.

Can anyone tell me what include actually does behind the scenes, and how to reverse this?

解决方案

module Mod
  def foo
    puts "fooing"
  end
end

class C
  include Mod
  def self.remove_module(m)
    m.instance_methods.each{|m| undef_method(m)}
  end
end

>> c = C.new
>> c.foo
fooing
>> C.remove_module(Mod)
=> ["foo"]
>> c.foo
NoMethodError: undefined method `foo' for #< C:0x11b0d90>

这篇关于如何反转ruby的include函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆