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

The Spells

Around Alias

Call the previous, aliased version of a method from a redefined method.

 
class​ String
 
alias_method :old_reverse, :reverse
 
 
def​ reverse
 
"x​#{old_reverse}​x"
 
end
 
end
 
 
"abc"​.reverse ​# => "xcbax"

For more information, see page Around Alias.

Blank Slate

Remove methods from an object to turn them into Ghost Methods (Ghost Method).

 
class​ C
 
def​ method_missing(name, *args)
 
"a Ghost Method"
 
end
 
end
 
 
obj = C.new
 
obj.to_s ​# => "#<C:0x007fbb2a10d2f8>"
 
 
class​ D < BasicObject
 
def​ method_missing(name, *args)
 
"a Ghost Method"
 
end
 
end
 
 
blank_slate = D.new
 
blank_slate.to_s ​# => "a Ghost Method"

For more information, see page Blank Slate.

Class Extension

Define class ...

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