Delegating methods in Ruby
Sometimes, when constructing a compound object, we are interested in exporting
functionality while retaining encapsulation. For example, suppose we have a
Secretary
class:
|
|
Our Secretary
provides a lot of useful functionality, that our Boss
class
would like to have. Boss
would like to be able to say that he can send a fax,
without having the user explicitly request his Secretary
beforehand. The same
goes for a lot of other methods Secretary
provides. Instead of writing a stub
function for each of these methods, it would be nice to do the following:
|
|
Here’s how we can get this to happen:
|
|
This solution does have its drawbacks - it will not work for methods which are
meant to accept blocks. I’m not sure how to get that to happen, short of using
a string-based class_eval
, which I’m not very fond of. (I find eval
to be,
well, evil…)