Photo by Planet Volumes🪐 on Unsplash

Metaprogramming: Ruby Hook Methods

Tech - RubyCademy
RubyCademy
Published in
2 min readMar 27, 2018

--

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

produces

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.

Class#inherited

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

produces

Tenant is a kind of user

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

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

Conclusion

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.

Ruby Mastery

We’re currently finalizing our first online course: Ruby Mastery.

Join the list for an exclusive release alert! 🔔

🔗 Ruby Mastery by RubyCademy

Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.

💚

--

--