Metaprogramming: Ruby Hook Methods

Mehdi Farsi
Mar 27, 2018 · 2 min read

Ruby comes with a bunch of hook methods that allow you to manipulate classes, modules and objects on the fly.

Here is a list of the most important hook methods:

  • Module#included
  • Module#extended
  • Module#prepended
  • Class#inherited

included, extended and prepended modules

These hook methods are invoked whenever a module is included, extended or prepended in another module or class.

They work pretty similarly. So here we’re going to detail the included hook method


The MediumPost entity now accepts comments !

This hook method allows you to add methods and attributes according to the class/module that includes the module where the hook method is defined.

This mechanism is actually used by the ActiveSupport::Concern module.

The implementation is pretty similar for theModule#extended and Module#prepended hook methods.


This hook method is called whenever a subclass of the class that implements the hook method is created


Tenant is a kind of user

This hook method is pretty handy when you want to define a variable or a class_attribute at class definition for each children.

That’s exactly what the ActiveRecord::Core module does with the class method.


Hook methods can be pretty handy for class and module manipulation on the fly.

However, as they modify the module/class blueprint, it can provoke some undesired side effects like superclass method overriding, etc..

I’ll detail the BasicObject#method_missing hook method in another article.

Voilà !


Feel free to subscribe here:

Thank you for taking the time to read this post :-)

Feel free to 👏 and share this article if it has been useful for you. 🚀

Also, as I post an article every 3 days, feel free to follow me to be notified of my new releases.

Here is a link to my previous article: .


E-Learning platform for Ruby and Ruby on Rails

Mehdi Farsi

Written by

Founder of — I blog about Ruby & ROR - Paris


E-Learning platform for Ruby and Ruby on Rails

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade