Rails使用内部REST API

Lee*_*Lee 2 rest ruby-on-rails

单独的REST JSON API服务器和客户端?

我正在寻找有关如何使用我自己的API(比如Twitter,据说)我计划制作的应用程序的建议.

我想有一个REST API,然后我可以将其用于Web应用程序,Android应用程序和一些分析/仪表板应用程序.

Rails有一个respond_with选项,我看过一些有html和json选项的应用程序,但我认为这是一种不那么出色的做事方式,json是数据,html用于演示,而你没有使用你的json API本质上

这看起来很愚蠢,但如果我想做一个服务器端的HTML解决方案,我究竟会如何使用Rails的REST api?使用像HTTParty这样的东西似乎很多工作,是否有更直接访问API的方法(例如,在ASP MVC中,您可以实例化一个控制器类,然后调用其方法.)

cal*_*las 5

您可以使用HTTParty并通过包含ActiveModel模块来创建类似于rails模型的客户端模型类.

activeresource gem在以前的rails版本中使用过,但他们不赞成使用HTTParty + ActiveModel类似的解决方案.

更新

我已经用基本的想法制作了这个例子(来自记忆),并不是一个完整的实现,但我想你会得到这个想法.

class Post
  # Attributes handling
  include Virtus

  # ActiveModel
  include ActiveModel::Validations
  extend ActiveModel::Naming
  include ActiveModel::Conversion

  # HTTParty
  include HTTParty

  # Virtus attributes
  attribute :id, Integer
  attribute :title, String
  attribute :content, Text # not sure about this one, read virtus doc

  # Validations
  validates :title, presence: true

  def save
    return false unless valid?

    if persisted?
      self.class.put("/posts/#{id}", attributes)
    else
      self.class.post("/posts", attributes)
    end
  end

  # This is needed for form_for
  def persisted?
    # If we have an id we assume this model is saved
    id.present?
  end

  def decorate
    @decorator ||= PostDecorator.decorate(self)
  end
end
Run Code Online (Sandbox Code Playgroud)

宝石需要:

  • httparty
  • activemodel(存在于rails中)
  • VIRTUS
  • 德雷珀