Rails consuming internal REST API
Separate REST JSON API server and client?
I am looking for advice on how to consume my own API (like Twitter is said to) for an app that I plan on making.
I would like to have a REST API that I can then use for an web app, Android app and some analytics/dashboard apps.
Rails has a respond_with option, and I have seen some apps that have an html and json option, but I think that is a less than stellar way of doing things and json is data and html is for presentation, and you are not making use of your json API essentially
It seems stupid but how exactly would I use my REST api from Rails if I want to do a server side html solution? Using something like HTTParty seems like a lot of work, is there a way to access the API more directly (in ASP MVC for example you can instantiate a controller class and then call its methods for example.)
You can use HTTParty and create client model classes that resemble a rails models by including ActiveModel modules.
activeresource gem was used in previous rails versions, but they deprecated it in favor of HTTParty+ActiveModel like solutions.
Update
I have crafted this example (from memory) with the basic ideas, is not a full implementation but I think you will get the idea.
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
gems needed:
下一篇: Rails使用内部REST API