15 Callbacks, hooks, and runtime introspection
Ruby provides a rich set of runtime hooks and reflective tools that let programs react to events as they happen and inspect their own structure while running. Callbacks such as method_missing, included, extended, inherited, const_missing, method_added, and singleton_method_added can be used to intercept missing methods, module mix-ins, extensions, subclassing, unresolved constants, and newly defined methods. These hooks are per class or per object, making them precise tools for shaping behavior without adding a lot of boilerplate.
The chapter then explores how Ruby lets you query capabilities at runtime. Using methods like methods, private_methods, protected_methods, instance_methods, public_instance_methods, singleton_methods, and their variants, you can inspect what an object, class, or module can do, and even compare method lists to discover overrides or inheritance relationships. The text emphasizes filtering and combining these lists to answer practical questions, such as which bang methods lack non-bang counterparts or which classes override methods from Enumerable.
Finally, the chapter shows how Ruby can reveal what variables are in scope and how execution arrived at a given point. You can inspect local, global, instance, class, and constant-related state, and use caller or caller_locations to work with stack traces in either string form or as structured location objects. The chapter culminates in a small test framework that uses callbacks, method inspection, and stack introspection to automatically run test methods, execute setup code, and report assertion failures with useful location information, demonstrating how these features can be combined into practical metaprogramming.
Summary
- method_missing, along with respond_to? and respond_to_missing?, offers a versatile toolset for handling unrecognized messages dynamically.
- Runtime callbacks for classes and modules include inherited, extended, and included.
- If defined, method_added and singleton_method_added are called when those events take place.
- Objects can be queried about their available methods, based on access level (public, for example) and whether the methods are singleton methods or not.
- Defining const_missing allows interception of unknown constant references.
- Stack traces provide information about where in the code a given event occurred, and can be intelligently queried through the use of caller_locations. .
- Taken together, Ruby’s callback and runtime introspection facilities teach you a lot about the language, while also providing a practical and powerful programming toolset.
The Well-Grounded Rubyist, Fourth Edition ebook for free