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.
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
You can use you json data like so
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.
By Dr Nic Williams May 22, 2012 - 7:14 pm
If the body is a nested hash, will all the nested hashes/objects within the json body be recursively wrapped?
By admin May 22, 2012 - 7:45 pm
It doesn’t look like ostruct will nest by default, this post seems to show how you do that http://www.rubyquiz.com/quiz81.html
By Dennis May 22, 2012 - 7:29 pm
It also works pretty great with Hashie (https://github.com/intridea/hashie), as Hashie also lets you access deeply nested attributes via methods.
By admin May 22, 2012 - 7:46 pm
I wish I had known about hashie earlier.
By trans May 24, 2012 - 11:44 am
Might be interested in http://github.com/rubyworks/ostruct2. It has a nested constructor.