Hooks & Concerns

Ruby tells you when things happen to a class

Classes and modules have lifecycle hooks β€” methods Ruby calls automatically at key moments:

  • included(base) β€” fired when a module is included into base.
  • extended(base) β€” fired when a module extends an object.
  • inherited(subclass) β€” fired when a class is subclassed.
  • method_added(name) β€” fired when a method is defined.

These are the seams Rails hooks into to inject behavior at exactly the right moment. included is the star: it's how a module can add both instance methods and class methods when mixed in.

In an interview, say: "included, inherited, and friends are runtime hooks Ruby fires during class construction. Rails uses included to inject class-level macros when a concern is mixed in β€” that's the whole mechanism behind ActiveSupport::Concern."