I have a module:
module MM::NN
def test_method
puts "module method called"
end
end
I am trying to include this module in a class A
per instance depending on a parameter passed to the initializer of the instance:
class A
def initialize(add_module)
self.class.send(:include, MM::NN) if add_module
end
end
I expected:
A.new(true).test_method # >> module method called
A.new(false).test_method # >> NoMethodError
But test_method
is defined on all instances. Calling the class with argument true
adds the module to the instances created later as well. I got:
A.new(true).test_method # >> module method called
A.new(false).test_method # >> NoMethodError
Initializing the class with false
argument on first initializer call and true
in the second will give the desired result, as test_method
method is added later:
A.new(false).test_method # >> NoMethodError
A.new(true).test_method # >> module method called
because the module is attached to the class itself.
How can I make the method available on specific cases like above?
How do i solve an another case:
where class A
inherit properties and methods of another class B
and class B
as well contains test_method
. How is it possible to use the module TestModule
s test_method
instead of method inside the class B
.
And what are the differences(or)side-effects in calling methods by including a module inside a class:
1) include module outside initialize.
2) Include module inside initialize.