Talking about ruby and other stuff.

Refactoring Wrappers

Introduction

Very often in my everyday practice I faced a task when you need to create a communication between your own services or some 3rd party service that don’t have a implementation yet. So what is the best way to doing that?

Wrapper - it is a piece of code that will be responsible for communication between your application and external service.

Identicating problem

When you have a task that implies creation of wrapper you could came up with the easiest solution like:

This doesn’t even looks like a object oriented approach, this is complete mess that could be extended became even worse. So what we could do about that?

Understanding problem

When you develop application especially application in ruby(You remember that this is Object Oriented language, right?) you should keep in mind what objects you create and how messages goes thought them. Let’s indicate our objects regarding this task scope:

Server

Platform

Notification

So basically we have:

Initiate Server creation ( isn’t this sounds like Object#new? )

Server down ( isn’t this changing the state of object ? )

Same for platform

Simple notifications that actually could be treated exactly how you think about your mailers

Solution

Now we see what objects we have, lets write simple implementations for Server.

From your code it will looks like this Wrapper::Server.new(@server).save! name it as a wrapper is a bad idea, so you should probably name it with a service_name and add Wrapper and the end if necessary. Let’s see how request will looks like:

12345678910111213

moduleWrapper::RequestclassError<StandardError;enddefself.post(url,params={})response=RestClient.post(Settings.service_url+url,params.to_json,content_type::json,accept::json)Wrapper::Response.new(response.body)rescueRestClient::Exception=>eWrapper::Response.new(e.response)rescueErrno::ECONNREFUSED=>eraiseWrapper::Request::Error,"Service is down"endend