Recently, we added WebSockets support to our application so the server could tell connected clients about great things that just happened. Our frontend, an Angular 5 app, really loves itself some lowerCamelCase property keys. Our backend, a Rails 5 API, was doing the work for application/json HTTP responses. We didn’t want to reinvent the wheel so we decided it was worth a peek to see how the existing solution could be leveraged for our newfangled WebSocket correspondence.

OliveBranch is the gem the backend was using to ensure JSON keys were lowerCamelCase by the time our frontend received an HTTP response. Dead simple to get working. Maybe it would be dead simple to re-use for data sent over WebSockets?

We were using OliveBranch 1.2.3 and from looking at the code it looked like we were SOL. There was no clean way to re-use the functionality. Why SOL? Here’s what we saw when we took at peek at the implementation. The relevant code is from OliveBranch’s middleware.rb. Look at its call method starting on line 12:

This file was strictly built as Rails middleware for the HTTP request/response cycle. You can tell because all of the transformation work is all kicked off inside of the call method and that method is very much coupled to the HTTP request/respnose cycle. Hrm. What are our options? Forcefully and awkwardly reuse this functionality? Nah, that sounds terrible and brittle. Find a different solution? Possibly. Roll our own? Ughhh, do we have to?

Before giving up we checked to see if the project had been updated. Fortunately, it had. Now OliveBranch had been updated to 2.1.1 (which is quite a jump from our current 1.2.3). Being curious minded people we revisited middleware.rb to see what may have changed. Here’s what we saw:

This code brought a smile to our developer-y faces. See that Transformations class? That, my friend, is an entry point to reusable code.

Here’s the snippet of code we ended up adding for our JSON payload just before we sent out the WebSocket correspondence:

We wrote a test, dropped that in, and voila: The love letters from the backend to the frontend needed no more translation once they arrived… and they lived happily ever after.

The end.

P.S. Happy coding.