Hooks

Ruby notifies you when a certain event happens, as shown in Table 2-2.

Table 2-2. Events and their hook methods

Event

Hook method

Of

Defining an instance method

method_added

Class

Defining a singleton method

singleton_method_added

Object

Make subclass

inherited

Superclass

These methods are called hooks. Ruby calls hook methods when the specific event occurs (at runtime). The default behavior of these methods is to do nothing. You have to override the method if you want to do something on a certain event:

class Foo
  def Foo::inherited(sub)
    printf "you made subclass of Foo, named %s\n", sub.name
  end
end
class Bar<Foo  # prints "you made subclass of Foo, named Bar"
end

There are other types of hook methods used by the mix-in feature. They are called by include and extend to do the actual mixing-in, as shown in Table 2-3. You can use these as hooks, but you have to call super when you override them.

Table 2-3. Mix-In hook methods

Event

Hook method

Of

From

Mixing in a module

append_features

Mix-in module

Module#include

Extending a object

extend_object

Mix-in module

Object#extend

Ruby 1.7 and later provide more hooks. See Chapter 6 for more information on future versions.

Get Ruby in a Nutshell 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.