Nino55 Nino55 - 6 months ago 25
Ruby Question

Re-Include Module

I need some like this:


module One
def test; puts 'Test One'; end
end

module Two
def test; puts 'Test Two'; end
end

class Foo
include One
include Two
include One
end


In this case I need as a result 'Test One' but obviously it returns 'Test Two'. I need a clean simple way for re-include my module.

Any suggestion?

Thanks!

Answer
 class Module
     def include_again(mod)
         mod.instance_methods.each { |m|
             self.send(:define_method, m) { |*args|
                 mod.instance_method(m).bind(self).call(*args)
             }
         }
     end
 end

module One
    def test(a); puts "test one #{a}"; end
end

module Two
    def test; puts "test two"; end
end

class Foo
    include One
    include Two
end

Foo.new.test #=> "test two"

class Foo
    include_again One
end

Foo.new.test(1) #=> "test one 1"