Read more

Rails: Overriding view templates under certain conditions only

Dominik Schöler
March 05, 2018Software engineer at makandra GmbH

Rails offers a way to prepend (or append) view paths for the current request. This way, you can make the application use different view templates for just that request.

Example

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

A use case of this is a different set of view templates that should be used under certain circumstances:

class UsersController < ApplicationController

  before_action :prepare_views
  
  def index
    # ...
  end    
  
  private
  
  def prepare_views
    if <condition>
      prepend_view_path Rails.root.join('app', 'views', 'special')
    end
  end
  
end

If <condition> is true, Rails will first look into app/views/special to find a view template. E.g. in this example, it would look for app/views/special/users/index.erb before trying the default app/views/users/index.erb.

If the desired template does not exist there, it will fall back to its standard view paths. This way you can customize select templates without needing to redefine all.

Warning

prepend_view_path has a memory leak in many versions of Rails. See the linked article for a fix.

Posted by Dominik Schöler to makandra dev (2018-03-05 08:35)