What is the opposite of Ruby's include?

Viewed 4202

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

Thanks.

6 Answers

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.

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.

Related