ruby-on-rails - 在另一个域上使用 RESTful Web 服务的正确 "Rails Way"是什么?

标签 ruby-on-rails rest

我想编写一个 Ruby on Rails 应用程序,它使用 RESTful Web 服务 API 对结果执行一些逻辑,然后在我的 View 上显示该数据。例如,假设我想编写一个在 search.twitter.com 上进行搜索的程序。使用纯 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

我很想将该方法作为私有(private)方法放入我的 Rails Controller 中,但我的一部分认为有一种更好、更“Rails”的方法来做到这一点。是否有最佳实践方法或者这确实是最好的方法?

最佳答案

有一个名为 HTTParty 的插件/gem,我已将其用于多个项目。

http://johnnunemaker.com/httparty/

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

对于 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')

最后一点,您也可以使用上面的代码,但一定要将该代码包含在模型中而不是 Controller 中。

关于ruby-on-rails - 在另一个域上使用 RESTful Web 服务的正确 "Rails Way"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/748614/

相关文章:

ruby-on-rails - Rails 4.0 在另一个范围定义中取消 default_scope 的方法(with_exclusive_scope depreciated)

ruby-on-rails - Rails 无法读取以 "false"值作为属性的 JSON 请求

javascript - 如何否定 ablFilter 中正在使用的过滤器

java - 使用 session 检查客户端是否在 REST API 中经过身份验证

asp.net-mvc - 具有复杂操作(动词)的 RESTful Web 服务

ruby-on-rails - rspec any_instance stub 不会重新启动旧实例

ruby-on-rails - 如何使用 Simple_form 但没有模型显示验证错误消息?

ruby-on-rails - Rails View 助手未将 HTML 插入页面

java - 将数据发布到 dropwizard 资源?

java - 使用 Apache Tomcat 在 Eclipse 中运行 RESTful Web 服务