Module: Padrino::Responders::Default
- Defined in:
- lib/padrino-responders/default.rb
Overview
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:
1) the responder searches for a template at extensions/index.xml;
2) if the template is not available, it will invoke <code>#to_xml</code> on the given resource;
3) if the responder does not <code>respond_to :to_xml</code>, call <code>#to_format</code> 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.
Instance Method Summary collapse
Instance Method Details
#respond(object, location = nil, kind = nil) ⇒ Object
:nodoc:
56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/padrino-responders/default.rb', line 56 def respond(object, location=nil, kind=nil) # :nodoc: if request.put? default_response_for_save(kind || 'edit', object, location) elsif request.post? default_response_for_save(kind || 'new', object, location) elsif request.delete? default_response_for_destroy(object, location) else default_response(object) end end |