【问题标题】:Consuming non-REST APIs in Rails with ActiveResource使用 ActiveResource 在 Rails 中使用非 REST API
【发布时间】:2010-02-17 00:59:12
【问题描述】:

我正在编写一个使用非 REST API(即 GET site.com/gettreasurehunts)的客户端,它要求我将请求的 HTTP 正文中的所有参数(甚至资源 ID)指定为自定义 XML 文档。 我想使用 Rails 和 ActiveResource,但我不得不重写几乎所有 ActiveResource 的方法。

是否有另一种更完善的方式来实现相同的结果,即使使用另一个 (Ruby) 框架?

【问题讨论】:

    标签: ruby-on-rails ruby http rest activeresource


    【解决方案1】:

    我认为 ActiveResource 没有办法做到这一点,对于这些情况,我只使用 Net::HTTP 和 Nokogiri

    【讨论】:

      【解决方案2】:

      我会推荐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 服务。

      【讨论】:

      • 在尝试 HTTParty 之后,我发现它有一些非常讨厌的错误(请查看我的问题以获取更多信息),我决定改用 Net::HTTP。还是谢谢你的回复!
      【解决方案3】:

      简单的答案,不要。我对 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'
        )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多