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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
  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

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 :