开发者

What is the opposite of Ruby's include?

开发者 https://www.devze.com 2022-12-16 15:26 出处:网络
If I have a class instance, containing several included modules, can I dynamically un-include a specific module (In order to replace 开发者_StackOverflow社区it)?

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

精彩评论

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

关注公众号