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!
Michael Gundlach
  • 106,555
  • 11
  • 37
  • 41

2 Answers2

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.

chrismear
  • 836
  • 8
  • 12
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/

Dale Zak
  • 1,106
  • 13
  • 22
  • The site is down but I tracked the post on his github (https://github.com/vaskas/vaskas.me/blob/master/blog/2012/02/07/using-hashes-as-activeresource-collections/index.html) - 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. – phillmv Apr 20 '14 at 00:33