Q - What happens when a module is included in a class?
A - As per the documentation,
Module#append_features is called by
Module#include which in turn adds the constants, methods and module variables.
Q - So how the members of a module be removed from a class?
A - Looks like there are two options. Use
Module#undef_method prevents the class from responding to calls from the method.
Module#remove_method completely removes the method from the class. What this means is that
Module#undef_method will cause a class to throw
NoMethodError even if the method is defined in a super class.
Module#remove_method will just remove the method from the class leaving the super class methods intact.
Module#remove_method looks a probable solution. So let's set up a test where a module called
Let's create a class
Hello that uses this module to get the name of the user and greet the user.
Lets add an
exclude method to
And finally, the actual test
When this test is executed the console output is
Q - So
Module#include is not literally including the methods in the
A - Yes and Ruby seems to be doing something else that makes it seem so. Thankfully, Ruby is Open Source and this function in MRI from the class.c file will answer our questions.
A cursory look at this function tells us that at line number 31 & 32, the module is inserted into the class hierarchy. This can be verified by printing
Q - Does Ruby provide a way to alter the class hierarchy?
A - No. So we'll have to make do with using
Module.undef_method instead of
Module.remove_method in our implementation of
Module.exclude. After swapping out
undef_method the exclude method works.
Oh and if someone is interested in building an
Object#extend in turn calls
Module#include so the procedure should be almost the same as for