MethodHuntingDelegator

— Paul Annesley, January 2012

I was implementing search in a Ruby app where the results objects were instances
of a mix of model classes. Each one had what could be considered a title and a
description, but the method names were inconsistent.

Wrapping each result in a SearchResult decorator to normalize the interface
seemed like a good idea. Ruby provides an abstract Delegator and a concrete
SimpleDelegator which gets most of the way there.

To normalize the method interface, I wrote an extension of SimpleDelegator
with a #hunt_and_call(*candidates) method, which finds and calls the first
method of the candidate list which the delegate responds to.

Here’s the example calling code:

And the MethodHuntingDelegator implementation:

And of course:

Completely insane? Useful enough for a gem? Better way of going about it? Give
me hell in the gist comments.

← index