This component is used to create slim controllers without unnecessery and repetitive code.
You can install Padrino responders via rubygems:
gem install padrino-responders
Now register responders in your application:
class SampleApp < Padrino::Application register Padrino::Mailer register Padrino::Helpers register Padrino::Responders ....
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 respond(@examples = Example.find(:all)) 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.
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, url(:users_show, :id => @user.id)) 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.
-
Fork the project.
-
Make your feature addition or bug fix.
-
Add tests for it. This is important so I don’t break it in a future version unintentionally.
-
Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
-
Send me a pull request. Bonus points for topic branches.
Copyright © 2010 Kriss ‘nu7hatch’ Kowalik. See LICENSE for details.