Usually we use delegation to help separate responsibilities and avoid mashing all responsibility and logic into the the one object. This is a great goal and the first one SOLID lists. For those who might not have seen a concrete example of delegation, let me run through a recent example I worked on.
We decided it would be nice to add a
voice qualifier or namespace to the gem so that we could group all the voice resources together. The main client class used
method_missing to work out what resource class to create. In order to do this we had to find some way to allow the client class do this whether you called
The solution was to use the Ruby
SimpleDelegator class to proxy all method calls to
voice back onto
self, something like this:
module ZendeskAPI class Delegator < SimpleDelegator; end class Client def voice Delegator.new(self) end end end
That’s pretty much as simple a delegator as you can get, works well out of the box and got the job done very effectively. Hopefully this will give others some inspiration on how to start delegating nicely.