我正在编写一个使用非 REST API(即 GET site.com/gettreasurehunts)的客户端,它要求我将请求的 HTTP 正文中的所有参数(甚至资源 ID)指定为自定义 XML 文档。我想使用 Rails 和 ActiveResource,但我不得不重写几乎所有 ActiveResource 的方法。
即使使用另一个(Ruby)框架,是否还有另一种更优雅的方式来实现相同的结果?
我正在编写一个使用非 REST API(即 GET site.com/gettreasurehunts)的客户端,它要求我将请求的 HTTP 正文中的所有参数(甚至资源 ID)指定为自定义 XML 文档。我想使用 Rails 和 ActiveResource,但我不得不重写几乎所有 ActiveResource 的方法。
即使使用另一个(Ruby)框架,是否还有另一种更优雅的方式来实现相同的结果?
我认为 ActiveResource 没有办法做到这一点,对于这些情况,我只使用 Net::HTTP 和 Nokogiri
我会推荐HTTParty,它非常灵活,我确信能够处理你需要的东西。
该项目的一些示例:
pp HTTParty.get('http://whoismyrepresentative.com/whoismyrep.php?zip=46544')
pp HTTParty.get('http://whoismyrepresentative.com/whoismyrep.php', :query => {:zip => 46544})
@auth = {:username => u, :password => p}
options = { :query => {:status => text}, :basic_auth => @auth }
HTTParty.post('http://www.twitter.com/statuses/update.json', options)
如果您需要在请求正文中发布某些内容,只需将 :body => "text" 添加到选项哈希中。
它使用起来非常简单,我目前正在使用它来代替 ActiveResource 来使用 Rails 应用程序中的一些 REST 服务。
简单的回答,不要。我对 ActiveResource 也有类似的问题,不喜欢 HTTParty 的 api(太多的类方法),所以我自己推出了。试试看,它叫做Wrest。它通过开箱即用的 REXML、LibXML、Nokogiri 和 JDom 部分支持 Curl 和反序列化。您也可以轻松编写自己的反序列化器。
这是 Delicious api 的示例:
class Delicious
def initialize(options)
@uri = "https://api.del.icio.us/v1/posts".to_uri(options)
end
def bookmarks(parameters = {})
@uri['/get'].get(parameters)
end
def recent(parameters = {})
@uri['/recent'].get(parameters)
end
def bookmark(parameters)
@uri['/add'].post_form(parameters)
end
def delete(parameters)
@uri['/delete'].delete(parameters)
end
end
account = Delicious.new :username => 'kaiwren', :password => 'fupupp1es'
account.bookmark(
:url => 'http://blog.sidu.in/search/label/ruby',
:description => 'The Ruby related posts on my blog!',
:extended => "All posts tagged with 'ruby'",
:tags => 'ruby hacking'
)