Using ostruct to interface with REST

Have you ever had to work with an external API such as twitter or facebook, those two should be pretty easy to interface with by now as there are plenty of wrappers such as koala.

But let’s say the API we are working on is a client’s API or the API for an obscure service.

What we want is for JSON requests to relate to ruby objects.

This is where ostruct comes along, ostruct takes a hash and converts that to methods that can be accessed as they were from an activerecord object for example.

What you can do is something similar to this.

query = "/notes/1"

c = Curl::Easy.perform(query) do |curl|
  curl.headers["X-Auth-Token"] = "my_auth_token"
end

my_hash = JSON.parse(c.body_str)

ostruct = OpenStruct.new(my_hash)

In this example i used curb to send an x-auth header to the “secret” api, and then passed the parsed json hash to ostruct.

Now rather than having to handle the json api like this in your views

<%= my_hash[:my_attrib] %>

You can use you json data like so

  <%= my_ostruct.my_attrib %>

This way if your boss falls out with the api company and wants you to re-implement the data in your rails app, all your view logic will be compatible with activerecord for example.

In my production code the post, get (other CRUD actions if needs be) and login actions are abstracted into a separate class and is inherited by each model.

3 thoughts on “Using ostruct to interface with REST