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!
4

2 回答 2

10

是的,ActiveResource 目前在数据格式方面有点不灵活。

JsonWithRootFormat原则上,这个想法是您可以基于该模块为自己编写一个自定义格式模块(例如),ActiveResource::Formats::JsonFormat然后将其指定为您的模型中的格式:

self.format = :json_with_root

但是,ActiveResource::Base它不是非常与格式无关——它当前会检查您是否正在使用XmlFormat,并且仅在您使用时才通过根节点。

所以你可以通过制作自己的格式模块和猴子补丁来获得你想要的东西ActiveResource::Base,但这并不理想。不过,我敢肯定,Base会欢迎使用与格式无关的补丁。

于 2009-05-22T12:49:13.447 回答
0

这是@vaskas的一篇很好的博客文章,解释了如何编写自己的自定义 ActiveResource Formatter。

使用哈希作为 ActiveResource 集合

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

于 2013-11-23T17:58:32.353 回答