Ruby: decorate methods with .method_added

Posted by Kevin Soltysiak on October 14, 2015 Topics: ruby

If you have been using Ruby (or Rails) long enough, you've probably encountered something like this :

Projects such as thor and grape make heavy use of those constructs, but they're far from being the only ones.

I always wondered how this was achieved, so the other day I finally decided to crack it open, and it turns out it is pretty easy.

It all boils down to one method, Module.method_added: this "hook" is called each time a method is defined on its caller:

First, you have to define class methods that mainly serves to keep track of your methods' metadata (or decorations, or annotations; call it as you see fit). Then, in method_added, you do all the processing you need, and do not forget to clean the metadata at the end.

Our previous example is pretty straightforward. What if we wanted to decorate our methods, as in Python? Here goes:

I do not know what the impact on performance is though, so you might want to check that before using this in production apps.

If you are into decorators, you should check michaelfairley/method_decorators, which includes commonly-used decorators and provides a starting point for your own.

If you have feedback or questions, please leave a comment, send me a mail, of hit me up on twitter.