Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 134 ยท Metaprogramming

Hooks and Callbacks

Learn Ruby hooks: inherited, included, extended, prepended, method_added and const_missing. Build plugin registries and class-level DSLs safely.

Ruby tells your code when something interesting happens to a class or module. When a class gets a subclass, when a module is mixed in, when a method is added: Ruby calls a hook method at that moment, and you can override it to react. Hooks are how libraries notice their own plugins, how include Comparable-style modules add class methods, and how frameworks keep track of every subclass without being told about it.

All hooks are ordinary methods with well-known names. Their default implementations do nothing, so overriding one is safe, as long as you remember to call super when you are inside a hierarchy that also uses the hook. In this lesson you will meet the most useful ones, build a plugin registry and a "mixin with class methods", and learn the traps.

inherited: a class gets a subclass

inherited(subclass) is called on the parent class every time someone writes class Child < Parent.

Ruby Tracking subclasses with inherited

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The hook runs as soon as the subclass is created, which is before its body has been evaluated. At that moment subclass.name already works for a named class, but the methods and constants of the new class do not exist yet. If you need to inspect the finished class, record it and look later (for example when the registry is first used).

The super call at the top matters. Class#inherited itself does nothing, but another library in the hierarchy may rely on it, so always chain.

Ruby 3.1 added Class#subclasses, which returns the direct subclasses without any hook: Shape.subclasses. Use that when you only need to list subclasses; use inherited when you must react.

included, extended and prepended

Three hooks run on a module when it is mixed into something:

Hook Triggered by Receives
included(base) include Mod the class or module that included it
extended(base) extend Mod the object or class that was extended
prepended(base) prepend Mod the class that prepended it

The famous use is the "include adds class methods" idiom. A plain include only adds instance methods; to also add class methods, the module extends the base from its included hook.

Ruby A mixin that brings class methods along

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output starts with Validatable included in Person, then [:name, :email], true and false. When include Validatable runs, Ruby calls Validatable.included(Person). The hook extends Person with ClassMethods, so validates_presence_of becomes callable in the class body, exactly like Rails' validates. This single pattern (a module with an included hook and a nested ClassMethods) underlies a large share of Ruby library code.

If your module is only about class methods, skip the hook and let users write extend. The hook is worth it when a module needs both instance and class behavior from a single include.

extended and prepended work the same way. For prepended, the typical job is wrapping methods of the base class, which you will meet in Monkey Patching and Safe Alternatives.

Ruby extended and prepended hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Because Loud sits in front of Dog in the ancestors list, Loud#speak runs first and its super reaches the class's own method. The same module extended onto a single object also wraps that object's singleton method.

method_added and friends

method_added(name) is called on a class or module whenever an instance method is defined in it, whether by def, define_method or attr_*. The singleton versions singleton_method_added (for singleton methods) and method_removed/method_undefined complete the family.

A classic trick is to wrap each new method, for example to log calls. You must guard against infinite recursion: wrapping defines a method, which triggers method_added again.

Ruby Wrapping every method as it is defined

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

extend Traced makes method_added a class method of Calc (the hook is called on the class itself), so it fires for every def after the extend. The @wrapping flag stops the hook from reacting to the method that define_method creates inside it. This works, but it is clever: the safer, more modern way to wrap methods is prepend with a module (see the monkey-patching lesson). Use method_added when the wrapped set is genuinely "whatever the user defines next", such as a before_action-style macro.

const_missing and method_missing's cousins

Module#const_missing(name) is called when Ruby cannot find a constant. Autoloaders and test helpers use it to load code on demand; here it simply produces a helpful message or a default.

Ruby const_missing and a graceful failure (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first Units::Foot prints (creating Foot) and the value; the second finds the constant that const_set just stored, so the hook does not run again. Units::Parsec calls super, which raises NameError with the usual message: main.rb:9:in 'Units.const_missing': uninitialized constant Units::Parsec (NameError). As with method_missing, handle only what you know and let everything else go to super.

Modern Ruby apps rarely write const_missing by hand: use autoload or a loader library such as Zeitwerk for lazy loading.

A plugin registry with inherited

Putting hooks together, here is a small but realistic design: a base class that collects every subclass in a registry keyed by a name, so plugins register themselves just by being defined.

Ruby Self-registering plugins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice that instance variables on a class belong to that class object and are not inherited, so each subclass starts with its own @registry equal to nil. The inherited hook gives subclasses a clean slate, while Exporter.registry keeps the shared table. (The "json" exporter is a toy that prints Ruby's inspect format, which is why its output looks like nested arrays.) The failing last line ends the program with main.rb:19:in 'block in Exporter.for': unknown format: xml (ArgumentError), which shows how a missing plugin should be reported. The pattern is exactly how many gems discover adapters.

Other hooks worth knowing

  • extend_object, append_features and prepend_features are the lower-level methods that extend, include and prepend call. Override them only for unusual tricks; extended, included and prepended are the hooks meant for ordinary use.
  • Object#singleton_method_added, Module#method_removed and Module#method_undefined fire on removal and undef.
  • Class#inherited also fires for Class.new(Parent), with an anonymous class whose name is nil at that moment.
  • Kernel#at_exit { ... } registers a block that runs when the program ends. It is a hook in spirit and useful for flushing logs.
  • Module#const_added (Ruby 3.2+) fires when a constant is defined.
Ruby Anonymous classes and at_exit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

For Class.new(Base) the hook sees nil, because the class has not been assigned to a constant yet. For Named = Class.new(Base) the assignment happens after the hook, so the name is still nil at that moment too, while class Normal < Base is already named when the hook fires. The at_exit block runs last, after the main program.

Pitfalls

  • Forgetting super. Overriding inherited or included without super can silently disable another library's hook.
  • Doing too much in the hook. In inherited, the subclass body has not run. Defer inspection, or use a method the subclass calls (like format_name above) to supply data explicitly.
  • Recursion in method_added. Defining methods inside it re-triggers it; use a guard flag.
  • Hidden control flow. Hooks run "by magic", which makes code harder to follow. Keep them short, document them, and prefer explicit calls (register :csv) when a hook adds little.
  • Testing. Subclasses defined in tests stay in registries forever. Clean up or isolate registries in test setup (see Testing with Minitest).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On which object is inherited(subclass) called when you write class Child < Parent?

    inherited is called on the parent class, with the new subclass as the argument.
  2. 2. Why does the common mixin idiom call base.extend(ClassMethods) inside self.included(base)?

    A plain include only adds instance methods. The included hook receives the base class and can extend it with class-level methods.
  3. 3. What is a risk when you define methods inside method_added?

    define_method and alias_method are method definitions too and re-trigger the hook unless you guard it.
  4. 4. When inherited runs, which of these is true?

    The hook fires when the class is created. Methods and constants defined in its body do not exist yet.
  5. 5. What should const_missing do for a constant name it does not recognize?

    As with method_missing, handle your own names and call super for the rest, so genuine typos still fail loudly.

Summary

  • Hooks are ordinary methods Ruby calls on events: inherited, included, extended, prepended, method_added, const_missing and more.
  • inherited runs on the parent when a subclass is created (before the subclass body); Class#subclasses lists subclasses without a hook.
  • Use included plus a nested ClassMethods module to give one include both instance and class behavior.
  • method_added can wrap methods but needs a recursion guard; prepend is usually safer.
  • Always call super in hooks, keep them short, and prefer explicit registration when magic adds little.

Next: instance_eval and class_eval