Padrino responders
This component is used to create slim controllers without unnecessery and repetitive code.
Installation
You can install Padrino responders via rubygems:
gem install padrino-responders
Now register responders in your application:
class Avaro < Padrino::Application
register Padrino::Mailer
register Padrino::Helpers
register Padrino::Responders
....
Getting started
Default responder is responsible for exposing a resource to different mime requests, usually depending on the HTTP verb. The responder is triggered when respond
is called. The simplest case to study is a GET request:
SampleApp.controllers :examples do
provides :html, :xml, :json
get :index do
@examples = Example.find(:all)
respond(@examples)
end
end
When a request comes in, for example for an XML response, three steps happen:
-
the responder searches for a template at extensions/index.xml;
-
if the template is not available, it will invoke
#to_xml
on the given resource; -
if the responder does not
respond_to :to_xml
, call#to_format
on it.
Builtin HTTP verb semantics
Using this responder, a POST request for creating an object could be written as:
post :create do
@user = User.new(params[:user])
@user.save
respond(@user)
end
Which is exactly the same as:
post :create do
@user = User.new(params[:user])
if @user.save
flash[:notice] = 'User was successfully created.'
case content_type
when :html then redirect url(:users, :show, :id => @user.id)
when :xml then render :xml => @user, :status => :created, :location => url(:users, :show, :id => @user.id)
end
else
case content_type
when :html then render 'index/new'
when :xml then render :xml => @user.errors, :status => :unprocessable_entity
end
end
end
The same happens for PUT and DELETE requests.