render default template when requested template is missing in Rails

Jeroen van Dijk picture Jeroen van Dijk · May 12, 2009 · Viewed 8k times · Source

For a plugin I want to hack the following feature into Rails:

When a (partial) template does not exist (regardless of the format) I want to render a default template.

So say I call an action 'users/index' if users/index.html.erb does not (or other format) exist, 'default/index.html.erb' should be rendered.

Similarly, If I call an action 'locations/edit' and 'locations/edit.html.erb' does not exist, 'default/edit.html.erb' should be rendered

For partials, If I call an action 'locations/index' and the template 'locations/index.html.erb' calls the partial 'locations/_location' which does not exist, it should render 'default/_object'

The solution is seek gives me access to the templates variables (e.g. @users, @locations) and information on the requested path (e.g. users/index, locations/edit). And it should also work with partials.

I have thought of some options which I'll post below. None of them are completely satisfactory.

Answer

Jeroen van Dijk picture Jeroen van Dijk · May 12, 2009

Solution 2:

Use 'rescue_from' in ApplicationController



class ApplicationController > ActionController::Base
  rescue_from ActionView::MissingTemplate do |exception|
    # use exception.path to extract the path information
    # This does not work for partials
  end
end



Drawback: does not work for partials.