1.3 Being Inclusive

Module Inclusion

A very common occurrence - especially when writing a Module for a library - is knowing when that module has been included or mixed-into another Class or Module using Module#include.

Ruby provides the Module.included method to receive callbacks when this happens. Module.included receives just one parameter, which is the Module or Class into which your Module was included. Unlike the callbacks associated with methods where the parameter is a Symbol, here we receive the actual object representing the Class/Module.

As always, lifecycle callbacks are easiest to teach through exercises, so here is one for you now.


Add the "included" callback as a self method on SparringArea, accept one parameter - the class/module into which it's being included - and store it in @@included_into

Output Window

Object Extension

The Module#extended callback is triggered when an object is extended using Module#extend. The only difference is that Module#extended receives the object as a parameter as opposed to Module#included where the parameter is always either a Class or a Module.


Keep in mind that the Module#extended callback is a self method on the module and receives a single parameter which is the object that was extended (not its class or its name, but the object itself)

Output Window

Congratulations, guest!

% of the book completed


This lesson is Copyright © 2011-2024 by Sidu Ponnappa and Jasim A Basheer