您可以使用 HTTParty 并通过包含 ActiveModel 模块创建类似于 rails 模型的客户端模型类。
在以前的 Rails 版本中使用了 activeresource gem,但他们弃用了它,转而支持 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
所需宝石:
- 派对
- activemodel(存在于rails中)
- 美德
- 布帘