Monday, December 6, 2010

More DRY in Controllers with Rails 3.0.3

One of nice features of the new version of Rails is that Controllers are now more concise as far as what types of formats a action responds with.

Below is the old pre 3.0.3 style:




class VendorsController < ApplicationController
  # GET /vendors
  # GET /vendors.xml
  def index
    @vendors = Vendor.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @vendors }
    end
  end

  # GET /vendors/1
  # GET /vendors/1.xml
  def show
    @vendor = Vendor.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @vendor }
    end
  end
end


Is replaced by this (changes highlighted):

class VendorsController < ApplicationController
   respond_to :html, :xml, :json
  # GET /vendors
  # GET /vendors.xml
  def index
    @vendors = Vendor.all

    respond_with(@vendors)
    end
  end

  # GET /vendors/1
  # GET /vendors/1.xml
  def show
    @vendor = Vendor.find(params[:id])

    respond_with(@vendor)
    end
  end
end

No comments:

Post a Comment