*   \   &   ©   |   /   * *   \   &   ©   |   /   * *   \   &   ©   |   /   * *   \   &   ©   |   /   * *   \   &   ©   |   /   *

Always render Rails views without the full layout when using AJAX & degradable javascript

Rails-fu

Been neck-deep in Ruby on Rails the last few months, here’s my first nugget o’ code wisdom:

I swear by unobtrusive and degradable javascript, which means every single one of my Rails views may or may not be getting called via AJAX. Obviously you never want to render the full page layout when using AJAX, and noodling with “request.xhr?” and “:layout => false” around every render action is bad code smell.

Here’s a 4 liner to extend the ‘render’ method and check if the view, partial, RJS, EJS etc. are being called by an XmlHttpRequest, in which case we want to ignore the layout unless explicitly asked to. Throw it in your ApplicationController and degrade away!


def render(*args)
  	args.first[:layout] = false if request.xhr? and args.first[:layout].nil?
	super
end

Plugin version coming soon? I also hope to publish some of my snippets to degradably ajaxify your entire web app using jQuery in 10 lines or less!



Comment on this

Textile Help