Alias Chaining

As we’ve seen, metaprogramming in Ruby often involves the dynamic definition of methods. Just as common is the dynamic modification of methods. Methods are modified with a technique we’ll call alias chaining.[6] It works like this:

  • First, create an alias for the method to be modified. This alias provides a name for the unmodified version of the method.

  • Next, define a new version of the method. This new version should call the unmodified version through the alias, but it can add whatever functionality is needed before and after it does that.

Note that these steps can be applied repeatedly (as long as a different alias is used each time), creating a chain of methods and aliases.

This section includes three alias chaining examples. The first performs the alias chaining statically; i.e., using regular alias and def statements. The second and third examples are more dynamic; they alias chain arbitrarily named methods using alias_method, define_method, and class_eval.

Tracing Files Loaded and Classes Defined

Example 8-8 is code that keeps track of all files loaded and all classes defined in a program. When the program exits, it prints a report. You can use this code to “instrument” an existing program so that you better understand what it is doing. One way to use this code is to insert this line at the beginning of the program:

require 'classtrace'

An easier solution, however, is to use the -r option to your Ruby interpreter:

ruby -rclasstrace my_program.rb --traceout /tmp/trace ...

Get The Ruby Programming Language 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.