Delegating Nicely

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.

At Zendesk we have a public API client Ruby gem to talk to the Zendesk API. Since we are building out the Voice parts of this API, we had to add a few resources such as PhoneNumber to the Gem.

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 or client.voice.phone_numbers.first.

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

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.

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s