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. 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
def statements. The second and third examples
are more dynamic; they alias chain arbitrarily named methods using
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:
An easier solution, however, is to use the
-r option to your Ruby interpreter:
ruby -rclasstrace my_program.rb --traceout /tmp/trace ...