views:

42

answers:

2

Most of the time I don't want to render a layout when the request comes from AJAX. To this end I've been writing render :layout => !request.xhr? frequently in my controller actions.

How can I make this the default? I.e., I'd like to be able to write

def new
  Post.find(params[:id])
end

and have the functionality be

def show
  Post.find(params[:id])
  render :layout => !request.xhr?
end

(I'm fine manually specifying a layout in the rare cases in which I want to use one.)

+1  A: 

A normal after_filter won't work because we want to modify rendering.

How about hijacking render?

class ApplicationController < ActionController::Base

  private
  def render(options = nil, extra_options = {}, &block) 
    options = {:layout => !request.xhr?}.merge(options) unless options.nil?
    super(options, extra_options)      
  end
end

Set the layout when calling render to override it. A bit ugly but should work.

anshul
This won't work -- it just calls `render` immediately (before my controller has the opportunity to set up the environment for my view)
Horace Loeb
Of course, filters won't work here... my bad! Does the updated solution do the trick?
anshul
+1  A: 

How about this?

class UsersController < ApplicationController
  layout proc {|controller| controller.request.xhr? ? false: "application" }
end

Good thing about this approach is you can achieve the result using standard library.

KandadaBoggu