Ruby Hooks for Metaprogramming

Ruby Hooks for Metaprogramming

Overview

What is a Hook?
In programming, a hook is a place and usually an interface provided in packaged code that allows a programmer to insert customized programming. For example, a programmer might want to provide code that analyzed how often a particular logic path was taken within a program.

Ruby Hooks

Ruby lets you hook in and change a lot of behavior of the core language. Methods, constants, classes, variables… etc. Ruby lets you query them all, and change a lot about them.

Here’s summaries and links for all the hooks I could find:

Methods
- respond_to_missing? - A way to make sure your dynamic methods defined with method_missing also handle respond_to?
- method_missing - Called when a method cannot be found, potentially to allow dynamically defining one instead.
- method_added - Called whenever a method is added which can be used to modify the method.
- method_removed - Called whenever a method is removed.
- singleton_method_added - Method added to the singleton class of the object, to be callable just on this one instance.
- singleton_method_removed - Method removed from singleton class.
- method_undefined - A method has been undefined, with undef_method. Undef_method is different from remove_method because remove_method may still allow superclasses to define the method – undef_method means it’s gone entirely.
- singleton_method_undefined - Called when a singleton method is undefined entirely.
- initialize_copy - An optional callback when cloning any Object.

Classes
- inherited - A Ruby class is subclassed.

Modules
- append_features - A Module is included, and its constants, methods and variables used.
- included - A Module is included, which usually obsoletes “append_features”.
- extend_object - A Module extends an Object.
- extended - An Object is extended by a module, which mostly obsoletes extend_object.
- const_missing - A constant isn’t already present.

Marshalling
- marshal_dump - Called on an object to have it dump itself in Ruby Marshal format.
- marshal_load - Called on an object to have it load itself in Ruby Mashal format.

Coercion
- coerce - Called by the first type in a two-argument operator on the second argument, to make it turn into something the first argument can recognize.
- induced_from - Deprecated, please don’t use.
- to_i, to_f, to_s, to_a, to_hash, to_proc and others - Conversions, indicating that the object is being used as a type and should try to convert itself to that type.