什么是正确的“Rails 方式"?在另一个域上使用 RESTful Web 服务? [英] What is the proper "Rails Way" to consume a RESTful web service on another domain?

查看:31
本文介绍了什么是正确的“Rails 方式"?在另一个域上使用 RESTful Web 服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 Ruby on Rails 应用程序,它使用 RESTful Web 服务 API 对结果执行一些逻辑,然后在我的视图中显示该数据.例如,假设我想编写一个在 search.twitter.com 上进行搜索的程序.使用纯红宝石,我可能会创建以下方法:

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. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method:

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

我很想将该方法作为私有方法放入我的 Rails 控制器中,但我的一部分认为有一种更好、更Rails"的方式来做到这一点.是否有最佳实践方法或者这真的是最好的方法?

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. Is there a best practice approach or is this really the best way?

推荐答案

有一个名为 HTTParty 的插件/gem,我已经用于多个项目.

There is a plugin/gem called HTTParty that I've used for several projects.

http://johnnunemaker.com/httparty/

HTTParty 可让您轻松使用任何 Web 服务并将结果解析为哈希.然后你可以使用散列本身或用结果实例化一个或多个模型实例.我两种方法都做过.

HTTParty lets you easily consume any web service and parses results into a hash for you. Then you can use the hash itself or instantiate one or more model instances with the results. I've done it both ways.

对于 Twitter 示例,您的代码如下所示:

For the twitter example, your code would look like this:

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.

这篇关于什么是正确的“Rails 方式"?在另一个域上使用 RESTful Web 服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆