Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume JSON formatting with ruby's ActiveResource?

ActiveRecord introduced a change to its default JSON output format. It went from

{ "user": { some_junk } }

to

{ some_junk }

ActiveResource has apparently followed their lead, expecting to consume JSON as

{ some_junk }

I am trying desperately to consume a RESTful web service which emits

{ "user": { some_junk } }

Is there a way to tell my ActiveResource::Base class to do so? Here's my code.

class User < ActiveResource::Base
    self.site = "http://example.com/"
    self.format = :json
end

Update: I'm giving up on ActiveResource as broken for now, unless someone knows the answer; in the meantime, I was able to achieve the GET that I wanted via

require 'httparty' # sudo gem install httparty
result = HTTParty.get('http://foo.com/bar.json', headers => { "Foo" => "Bar"})
# result is a hash created from the JSON -- sweet!
like image 242
Michael Gundlach Avatar asked May 05 '09 20:05

Michael Gundlach


1 Answers

Yeah, ActiveResource is currently a bit inflexible when it comes to its data formats.

In principle, the idea is you could write yourself a custom format module (e.g. JsonWithRootFormat), based on the ActiveResource::Formats::JsonFormat module, and then specify that as your format in your model:

self.format = :json_with_root

However, ActiveResource::Base isn't very format-agnostic -- it currently does a check to see whether you're using XmlFormat, and only passes the root node through if you are.

So you could get what you wanted by making your own format module, and monkey-patching ActiveResource::Base, but it's hardly ideal. I'm sure a patch to make Base a bit more format-agnostic would be welcomed, though.

like image 126
chrismear Avatar answered Jan 30 '23 14:01

chrismear