简体   繁体   English

在另一个域上使用RESTful Web服务的正确“Rails方式”是什么?

[英]What is the proper “Rails Way” to consume a RESTful web service on another domain?

I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. 我想编写一个Ruby on Rails应用程序,它使用RESTful Web服务API对结果执行一些逻辑,然后在我的视图上显示该数据。 For example, let's say I wanted to write a program that did a search on search.twitter.com. 例如,假设我想编写一个在search.twitter.com上搜索的程序。 Using pure ruby I might create the following method: 使用纯ruby我可能会创建以下方法:

def run(search_term='', last_id=0)
  @results = []
  url = URI.parse("http://search.twitter.com")
  res = Net::HTTP.start(url.host, url.port) do |http|
    http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}")
  end
  @results = JSON.parse res.body
end

I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. 我很想把这个方法作为私有方法放到我的Rails控制器中,但我的一部分认为有更好的,更“Rails”的方法来做到这一点。 Is there a best practice approach or is this really the best way? 有最佳实践方法还是这是最好的方法?

There is a plugin/gem called HTTParty that I've used for several projects. 我有一个名为HTTParty的插件/ gem用于几个项目。

http://johnnunemaker.com/httparty/ http://johnnunemaker.com/httparty/

HTTParty lets you easily consume any web service and parses results into a hash for you. HTTParty允许您轻松使用任何Web服务并将结果解析为哈希。 Then you can use the hash itself or instantiate one or more model instances with the results. 然后,您可以使用散列本身或使用结果实例化一个或多个模型实例。 I've done it both ways. 我已经做到了两个方面。

For the twitter example, your code would look like this: 对于twitter示例,您的代码将如下所示:

class Twitter
  include HTTParty
  base_uri 'twitter.com'

  def initialize(u, p)
    @auth = {:username => u, :password => p}
  end

  # which can be :friends, :user or :public
  # options[:query] can be things like since, since_id, count, etc.
  def timeline(which=:friends, options={})
    options.merge!({:basic_auth => @auth})
    self.class.get("/statuses/#{which}_timeline.json", options)
  end

  def post(text)
    options = { :query => {:status => text}, :basic_auth => @auth }
    self.class.post('/statuses/update.json', options)
  end
end

# usage examples.
twitter = Twitter.new('username', 'password')
twitter.post("It's an HTTParty and everyone is invited!")
twitter.timeline(:friends, :query => {:since_id => 868482746})
twitter.timeline(:friends, :query => 'since_id=868482746')

As a last point, you could use your code above also, but definitely include the code in a model as opposed to a controller. 最后一点,您也可以使用上面的代码,但肯定包含模型中的代码而不是控制器。

Restclient is a really nice solution to this problem. Restclient是解决这个问题的一个非常好的解决方案。

require 'rest_client'
RestClient.get 'http://example.com/resource'
RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}}

From the readme . 自述

如果远程RESTful Web服务也是使用Ruby on Rails创建的,那么ActiveResource就是最佳选择。

为了回应您的Twitter示例,有一个Twitter Gem可以帮助您自动执行此操作。

I think Faraday deserves a mention here. 我认为法拉第在这里值得一提。 Really nice interface, and powerful concept of middleware. 非常好的界面,以及强大的中间件概念。

https://github.com/lostisland/faraday https://github.com/lostisland/faraday

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM