开发者

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 开发者_StackOverflow社区it)?

Thanks.


No. You can't un-include a mixin in the Ruby Language. On some Ruby Implementations you can do it by writing an implementation specific extension in C or Java (or even Ruby in the case of Rubinius), though.


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!"

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.


Try http://github.com/yrashk/rbmodexcl, which provides an unextend method for you.


Use the Mixology C extension (for MRI and YARV): http://www.somethingnimble.com/bliki/mixology


If you have already include-ed something, you can use load to re-include the file. Any definitions in the load-ed file will overwrite existing methods.


the true answer is refinement

please check this answer.

https://stackoverflow.com/a/19462745/1409600

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜