15.1. Callbacks and hooks

The use of callbacks and hooks is a fairly common meta-programming technique. These methods are called when a particular event takes place during the run of a Ruby program. An event is something like

  • A nonexistent method being called on an object
  • A module being mixed in to a class or another module
  • An object being extended with a module
  • A class being subclassed (inherited from)
  • A reference being made to a nonexistent constant
  • An instance method being added to a class
  • A singleton method being added to an object

For every event in that list, you can (if you choose) write a callback method that will be executed when the event happens. These callback methods are per-object or per-class, not global; if you want a method ...

Get The Well-Grounded Rubyist, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.