Dry api controllers using rails 3 responders

fabrik42 edited this page Jul 26, 2011 · 5 revisions

DRY Api Controllers using Rails 3 Responders

You can dry up your actions by setting the controller's responder to the ActsAsApi::Responder class.

With this in place, you can use the built-in respond_with method.

You can do this on a per-controller basis, or, you can create a parent class for your controllers to inherit from, as seen here.

Note that the :api_template parameter is where you specify which template you'd like to render, and is required on all respond_with calls.

class ApiController < ApplicationController
  self.responder = ActsAsApi::Responder
  respond_to :json, :xml
end

class UsersController < ApiController

  def index
    @users = User.all
    respond_with(@users, :api_template => :name_only, :root => :users)
  end

  # You're free to add additional options to the `respond_with` call, e.g., specifying a HTTP Location header.
  def show
    @user = User.find(params[:id])
    respond_with @user, :api_template => :name_only, :location => user_path(@user)
  end

  def new
    respond_with(User.new, :api_template => :name_only)
  end

  def create
    @user = User.create(params[:user])
    respond_with(@user, :api_template => :name_only)
  end

  def edit
    @user = User.find(params[:id])
    respond_with(@user, :api_template => :name_only)
  end

  # Note: if successful, Rails will return an empty object for JSON -> {}
  def update
    @user = User.find(params[:id])
    @user.update_attributes(params[:user])
    respond_with(@user, :api_template => :name_only)
  end

  def destroy
    @user = User.find(params[:id])
    respond_with(@user.destroy, :api_template => :name_only)
  end
end

Problems when you want to respond with a custom Hash instead of a model?

You want to check out this stackoverflow answer: http://stackoverflow.com/questions/5780856/rails-3-why-might-my-respond-to-statement-throw-this-exception-when-called-from

Author: johnreilly

2011-07-26: Update by fabrik42