Hooks
Ruby notifies you when a certain event happens, as shown in Table 2-2.
|
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"
endThere 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.
|
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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access