views:

268

answers:

5

Hello,

If I have a class instance, containing several included modules, can I dynamically un-include a specific module (In order to replace it)?

Thanks.

+2  A: 

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

eliah
+2  A: 

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.

Jörg W Mittag
+2  A: 

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.

Justin Weiss
A: 

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

banister
A: 

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.

bta