How to consume JSON formatting with ruby's ActiveResource?
Asked Answered
I

2

13

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!
Iselaisenberg answered 5/5, 2009 at 20:6 Comment(0)
C
10

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.

Chlori answered 22/5, 2009 at 12:49 Comment(0)
H
0

Here's a good blog post by @vaskas explaining how to write your own custom ActiveResource Formatter.

Using Hashes as ActiveResource Collections

http://vaskas.me/blog/2012/02/07/using-hashes-as-activeresource-collections/

Henriquez answered 23/11, 2013 at 17:58 Comment(1)
The site is down but I tracked the post on his github (github.com/vaskas/vaskas.me/blob/master/blog/2012/02/07/…) - gist of it is you can assign your own format object to self.format. Create a new class, include ActiveResource::Formats::JsonFormat and define your own decode function.Mortgage

© 2022 - 2024 — McMap. All rights reserved.