O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

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

8.8. Delegating Method Calls to Another Object

Problem

You'd like to delegate some of an object's method calls to a different object, or make one object capable of " impersonating" another.

Solution

If you want to completely impersonate another object, or delegate most of one object's calls to another, use the delegate library. It generates custom classes whose instances can impersonate objects of any other class. These custom classes respond to all methods of the class they shadow, but they don't do any work of their own apart from calling the same method on some instance of the "real" class.

Here's some code that uses delegate to generate CardinalNumber, a class that acts almost like a Fixnum. CardinalNumber defines the same methods as Fixnum does, and it takes a genuine Fixnum as an argument to its constructor. It stores this object as a member, and when you call any of Fixnum's methods on a CardinalNumber object, it delegates that method call to the stored Fixnum. The only major exception is the to_s method, which I've decided to override.

 require 'delegate' # An integer represented as an ordinal number (1st, 2nd, 3rd…), as # opposed to an ordinal number (1, 2, 3…) Generated by the # DelegateClass to have all the methods of the Fixnum class. class OrdinalNumber < DelegateClass(Fixnum) def to_s delegate_s = __getobj_ _.to_s check = abs if to_check == 11 or to_check == 12 suffix = "th" else case check % 10 when 1 then suffix = "st" when 2 then suffix = "nd" else suffix = "th" ...

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