liveBook · Manning

Inherited

As explained in The Well-Grounded Rubyist, Fourth Edition

inherited is a Ruby class method callback invoked on a class when that class is subclassed, receiving the new subclass as its argument.

Define inherited as a class method to intercept subclassing. Ruby calls it automatically with the new subclass, allowing the superclass to react whenever it gains a descendant. section 15.1.4

Report newly created subclasses

class C def self.inherited(subclass) puts "#{self} just got subclassed by #{subclass}." end end class D < C end # C just got subclassed by D section 15.1.4

The callback cascades through an inheritance chain: subclassing D can trigger inherited defined by C, because D retains the behavior inherited from C. It does not intercept inheritance of singleton classes, even when inherited is defined inside C’s singleton class. section 15.1.4

Building a MicroTest utility

MicroTest uses inherited to receive each testing subclass, then enters that subclass with class_eval and installs method_added. Newly defined test methods create an instance, run setup when present, and execute the test through send. This turns subclassing and method definition into automatic test discovery. section 15.5.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains callback definition, inheritance cascading, MicroTest integration, and singleton-class limits.
Examples
Uses reporting classes, deeper subclassing, singleton-class experiments, and a MicroTest-driven CardTest.
What it assumes
Assumes Ruby classes, class methods, inheritance, and method definitions; demonstrates class_eval and method_added in application.
What you can do after
Build it from scratch as a subclass hook that configures descendants or drives automatic test discovery.
How it connects
Connects class methods, inheritance, singleton classes, class_eval, method_added, and runtime callbacks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.