O'Reilly logo

Metaprogramming Ruby 2 by Paolo Perrotta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hook Methods

Where you get one of Bill’s thorough lessons in advanced coding.

The object model is an eventful place. Lots of things happen there as your code runs: classes are inherited, modules are mixed into classes, and methods are defined, undefined, and removed. Imagine if you could “catch” these events like you catch GUI mouse-click events. You’d be able to execute code whenever a class is inherited or whenever a class gains a new method.

Well, it turns out you can do all these things. This program prints a notification on the screen when a class inherits from String:

ctwc/hooks.rb
 
class​ String
 
def​ self.inherited(subclass)
 
puts ​"​#{self}​ was inherited by ​#{subclass}​"
 
end
 
end
 
 
class​ MyString < String; ​end

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required