Metaprogramming hooks

Ruby defines a few hook methods that you can use to detect when a class is subclassed or when a module is mixed in. These hooks are called inherited(), included() and extended().

If a class has a class method called inherited() it will be called whenever you create a subclass of it:

var ChildDetector = new Class({
    extend: {
        inherited: function(klass) {
            // Do stuff with child class
        }
    }
});

The hook receives the new child class as an argument. Note that class is a reserved word in JavaScript and should not be used as a variable name. The child class will have all its methods in place when inherited() gets called, so you can use them within your callback function.

In the same vein, if you include() a module that has a singleton method called included, that method will be called. This effectively allows you to redefine the meaning of include for individual modules.

The extended() hook works in much the same way as included(), except that it will be called when the module is used to extend() an object.

// This will call MyMod.extended(obj)
obj.extend(MyMod);

Again, you can use this to redefine how extend() works with individual modules, so they can change the behaviour of the objects they extend.