SuperPumpup (dot com)
General awesomeness may be found here.

05 February 2013

Translation In An API Client Gem

I went to the austin.rb meeting last night and enjoyed the talk. The speaker, @benhamill, asked for feedback and the thing that I've been thinking about since but is too long to tweet is his concept of Translation vs Transliteration of an API.

Briefly: most things you get out of an API are JSON objects, and accessors on JSON objects don't "feel" very "rubyish". For example:

  isAwesome: true,
  eatsBurritos: true,
  lastBurritoEaten: 230498234

The contention was that transliterating would get you methods like:

thing.isAwesome #=> true
thing.eatsBurritos #=> true
thing.lastBurritoEaten #=> 234093248

And those, correctly, feel wrong. And in fact, ruby's Rails's built-in string tools will readily convert this camelcase to snake case:

>> "lastBurritoEaten".underscore
=> "last_burrito_eaten"

In "bare" ruby you can "borrow the metaphor wholesale" and just copy ActiveSupport's implementation.

So these have been generally reanmed to more 'ruby-esque' names, and the output returned in a more sane matter (like last_burrito_eaten) returning a time object.


I do, however, have a problem with renaming the methods other than a straight conversion to underscore. Why would I care if my 'translator' changes isAwesome to awesome??

Two Kinds Of Consumer

The thing to remember is that your client gem will likely have at least two types of consumer. I know that I consume these gems in a couple of ways. Either a large part of my application is intimately involved in this API and my becoming fluent and awesome with this API is necessary for my app, and I will appreciate these conventians for making my life easier, OR (and this is more commonly how I consume these gems) this gem is a tiny part of my application put in for a small feature and my brain does not have space to remember how you translated.

This is a problem because the builder of the client gem most likely 1) has less documentation than the actual API provider, and 2) that documentation is GOING to get out of sync with the code - first the API code, then the gem's code - even if it were provided up front. So now, instead of looking at the service's API docs, seeing isAwesome and just calling .underscore, you have to remember (best case) or look up in docs (a bit of a pain but whatever) or even dig through your gem's source code (ugh).


Remember the consumer who will try to not read your gem's docs (even if you put them in the README), and will instead go for the principle of least astonishment in trying to use your gem. Keep the 'translation' as invisible to the user as possible. Hell, maybe even alias isAwesome to your new is_awesome method so that someone can just send the messages they see described in the API docs, even if they don't 'feel rubyish'.

Categories: Ruby on Rails Software