← Back to blog
· 2 min read · Rails3 RailsResponders

Rails 3 Responders

So we have a problem here in Controllers. As our application grows our controllers grows. We will be in trouble when we have alternative formats in our controllers like JSON, XML.

You might need to respond both in JSON and XML or might be only JSON in your controller. {% codeblock lang:ruby%} class BlogsController < ApplicationController def index @blogs = Blog.all respond_to do |format| format.html format.xml { render :xml => @blogs } end end

def show @blog = Blog.find(params[:id]) respond_to do |format| format.html format.xml { render :xml => @blog } end end end {% endcodeblock %}

You can see here that in both the action we are responding with HTML and XML.

Rails 3 introduced a new set of methods called responders that abstract the code so that the controller becomes much simpler.

Here is our example written using responders {% codeblock lang:ruby%} class BlogsController < ApplicationController respond_to :html, :xml

def index @blogs = Blog.all respond_with(@blogs) end

def show @blog = Blog.find(params[:id]) respond_with(@blog) end end{% endcodeblock %}

This looks more cleaner No ?

The entire respond_to block is gone now.

I know this feature is very old. But it's very important to use this feature for more cleaner code.

Reference links :