Twitter GitHub Facebook Instagram dirv.me

Daniel Irvine on building software

Rails pattern: repeated action with differing layout

12 August 2014

A repeated action is one which occurs on multiple controllers. In the following example, three controllers share a generate action.

class AdminController < ApplicationController
  layout admin
end

class A < AdminController

  def index
    render :index
  end

  # ... other actions

  def generate
    render :generate
  end
end

class B < AdminController
  def index
    render :index
  end
  
  # ... other actions

  def generate
    render :generate
  end
end

class C < AdminController

  def index
    render :index
  end

  # ... other actions

  def generate
    render :generate
  end
end

The call to class method layout on line 2 ensures that the layout file used for all of these controller actions is admin.html.erb. But what if we want to use a different layout for the generate action, without touching any of the other actions?

We do this using a different call to layout. It can take a method name which is then delegated to for each action call.

class AdminController < ApplicationController
  layout :select_layout

  def select_layout
    if action_name == 'generate'
      'special'
    else
      'admin'
    end
  end
end

See the layout API docs for more information.

About the author

Daniel Irvine is a software craftsman at 8th Light, based in London. These days he prefers to code in Clojure and Ruby, despite having been a C++ and C# developer for the majority of his career.

For a longer bio please see danielirvine.com. To contact Daniel, send a tweet to @d_ir or use the comments section below.

Twitter GitHub Facebook Instagram dirv.me