Camel Casing Your API Response in rocket_pants

March 17, 2015

What is rocket_pants?

Rocket pants is a gem that gives you a set of tools for building an API in Ruby with Rails.

Motivation for camel casing

The developer team decided we wanted to return camel-cased json responses, e.g.,

 

{ myResponse: “My response” }

 

Steps for camel casing

Since our Rails model attributes use the traditional snake case naming and rocket_pants by default in its response returns the default attributes, I needed a way to camel case the attribute names that were

returned in the response.

I’m omitting the steps you need (perhaps I’ll cover it in a future post if there’s demand for it), to install rocket_pants, but that’s pretty straightforward for the most part via the project’s README file.

Step 1 – Override the attributes method in your model.rb file

class Trial < ActiveRecord::Base
  def attributes
    info = { 'id' => nil, 'firstName' => nil, 'lastName' => nil, 'fullName' => nil }
    super.replace info
   end
end

Instead of replace, you could use merge but I used replace because replace ensures the API response when you call the expose method from rocketpants only contains the attributes in the _info hash. If I had used replace, then I would have gotten all the rest of the Trial model attributes.

If you need different responses for specific API versions, then you could override the serializable hash as indicated in this stackoverflow post

Step 2 -- camelize the model attributes using metaprogramming

Trial.attribute_names.each do |attribute_name|
  unless attribute_name == attribute_name.camelize(:lower)
    define_method attribute_name.camelize(:lower) do
      self.send(attribute_name)
    end
  end
end

In step 2, unless the model attribute is already camel-cased, I create one using define_method along with Rails’ camelize method.

Step 3 -- camel case any method names being passed in the API response

class Trial < ActiveRecord::Base
  def fullName
    first_name + last_name
  end
end

Notice how I have a camel-cased method called fullName which concatenates the first_name and last_name attribute values for the Trial model.

This is how you can customize your API response via rocket_pants.


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.