-
Notifications
You must be signed in to change notification settings - Fork 68
Declaring api templates for any class! (no orms)
fabrik42 edited this page May 14, 2011
·
2 revisions
In fact acts_as_api
can be used with any class to be rendered as json
or xml
.
You only have to do two things:
- extend the class with
ActsAsApi::Base
- implement a method called
model_name
to tellacts_as_api
how the model should be called
Here is a short example, based in this gist
require 'rubygems'
require 'active_model'
require 'active_support'
require 'json'
require 'acts_as_api'
class User
extend ActsAsApi::Base
attr_accessor :first_name, :last_name, :age, :active
def initialize(opts)
@tasks = []
opts.each do |k,v|
self.send :"#{k}=", v
end
end
def model_name
'user'
end
acts_as_api
api_accessible :name_only do |t|
t.add :first_name
t.add :last_name
end
end
# create a user
user = User.new({ :first_name => 'Luke', :last_name => 'Skywalker', :age => 25, :active => true })
# get the user data based on the passed api template
response = user.as_api_response(:name_only)
# show it to the world
puts response.inspect
# => {:first_name=>"Luke", :last_name=>"Skywalker"}