1.1 Introduction

The Hollywood Principle

When doing any metaprogramming, tracking changes to the runtime is a problem that you will encounter sooner or later.

Ruby offers programmers what are called "object lifecycle callbacks" to track such changes and respond to them. Worried that someone might override a method? Register a callback and you'll be notified when something happens. That's why it's called the "Hollywood Principle": you don't poll the runtime for changes; instead, the runtime calls you when something changes.

Example Code:

Output Window

Ruby offers a moderately comprehensive set of callbacks - like method_addded in the example above - allowing you to track many of the changes that can be made to a piece of code.

Tracking methods

The addition of a method to a class or module is a logical place to begin. method_added is an instance method on Module and consequently inherited into Class. When you're using it, you simply implement the method as an instance method on the class (or module) - so it's a self method, basically - and listen for the names of methods that are added.

The only information it receives from the runtime is the name of the method, in the form of a Symbol.

Lifecycle callbacks are simple enough to understand that you will understand it very quickly with a little practice. Here's an exercise for you to try it out - simply make the tests pass.

Hint

Make sure that method_missing is defined on Dojo itself and not on its instances.

Output Window

Tracking singleton methods is identical, except that you use the singleton_method_added lifecycle callback instead of method_added. singleton_method_added being of a more fundamental nature is defined on BasicObject.

The only interesting difference from method_added worth noting is that since singleton_method_added is itself a singleton method, it receives a callback - about itself - as soon as it's added.

Let's dive straight into an exercise.

Output Window

Singleton methods, but not Class methods

There's an important nuance that's worth understanding when dealing with singleton_method_added and method_added.

The most natural tack the mind takes with these two callbacks is to assume that method_added will observe instance methods and singleton_method_added, class methods. This, however, is not entirely true; Ruby's singleton object backs normal objects and contains object specific changes. For classes, these are class methods. But when adding a method to a single, regular object, adding instance methods to that object alone modifies the singleton object for that object.

Let me show you why by having you solve this exercise.

Output Window

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2014 by Sidu Ponnappa and Jasim A Basheer