This is a series about Ruby Patterns, which will explain some common uses of Ruby syntax. The second post is about a webservice based. I like to call it a pattern because it is very common and tends to repeat (on a not-duplicated way) on Service Oriented Architecture based applications. Of course, this code may be too sophisticated for such
a small script like this, but it may be a good way to handle things on a more complex application.
So, you’re given the task to write a class that access a webservice and returns the info on it (e.g. the github repos for a given organization). A simplistic implemetation can be like this:
Well, the public methods seems to be more concise now and we have extracted
some methods that can be more easily reused. But there is a few flaws: if we call
the repos method twice, it will make two requests, but this is easy to solve: just add some memoization.
The repos method seems simple enough now, and we have moved the parsing responsability to the get method. But we can get rid of it delegating to someone else to do that.
There is a great gem called faraday-middleware that parses it for me, based on the content type header
and returns a hash, so, let’s use it.
Neat! It is indeed really easy to add new endpoints support to our class. But I think it has a lot of responsability: it is dealing with the connection to the API. Let’s extract a new class that does that and refer to it on the client method.
Now we have a pretty simple class, which I finally consider a final implementation, it splits the responsability to parse to another place and now I only have to specify the endpoints and get (or post/put/patch/delete) it. Another improvements may be to add a condition to do something when we have a 404 on an endpoint.
What about you ? Would you recommend another improvement ? Do you use something similar ?