Ruby callbacks

This blog post is about ruby’s callbacks(hooks): what are the available ones,and how practically we can use them?


obj.method_missing(symbol [, *args] ) => result might be the most famous hook in ruby, and is being used a lot by ruby developers :

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior.

Here is a simple example where the user can mix colors using the mix method :

Now, how about letting the user do something like: ‘c.greenAndBlue’ or ‘c.grayAndYellow’ ?, let’s see how to do so:


const_missing : invoked when a reference is made to an undefined constant.

I will use it to show the user a more informative message when he tries to use a non existing constant:

included and extended

included and extended are fired when the module is included or extended :

However let’s move to a more practical use, if u look at the module documentation, you will find the following definition:

A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not.

Well, as you can see, you can’t include the module methods inside your class, then what to do?
I saw some people use a nice trick to do so, they split their module into 2 inner modules, one called InstanceMethods and the other called SingletonMethods, then they include the former, and extend the later, look at the following snippet of code :

method_added and singleton_method_added

method_added and singleton_method_added are another 2 callbacks that are fired when a new instance or singleton method is added.
In the code snippet bellow, I’m trying to prevent a developer from monkey patching(reopen) my colors class:

method_removed and method_undefined

method_removed: fired when an instance method is removed.
method_undefined: fired when an instance method is undefined.

singleton_method_removed and singleton_method_undefined

singleton_method_removed: fired when a singleton method is removed.
singleton_method_undefined: fired when a singleton method is undefined.


inherited is called when some class is being inherited:

A practical use will be in preventing subclasses from being created :

Well, that’s all for this post. The next post series will be on writing internal DSLs using ruby.
See you then…..