Skip to content

Instantly share code, notes, and snippets.

@ymendel
Created March 3, 2009 18:28
Show Gist options
  • Save ymendel/73443 to your computer and use it in GitHub Desktop.
Save ymendel/73443 to your computer and use it in GitHub Desktop.
This allowed for automatic render overrides based on controller
An example:
controller = UsersController
action = show
normal path = RAILS_ROOT/app/views/users/show.html.erb (or haml or rhtml or rjs or whatever)
With this in place,
first choice = RAILS_ROOT/app/views/general/_types/users/show.html.erb
second choice = RAILS_ROOT/app/views/general/show.html.erb
Similarly, with a specific render call
render :partial => 'form'
normal path = RAILS_ROOT/app/views/users/_form.html.erb
With this in place,
first choice = RAILS_ROOT/app/views/general/_types/users/_form.html.erb
second choice = RAILS_ROOT/app/views/general/_form.html.erb
Or with something more involved:
render :partial => 'some/shared/view'
normal path = RAILS_ROOT/app/views/some/shared/_view.html.erb
With this in place,
first choice = RAILS_ROOT/app/views/general/some/shared/_types/users/_view.html.erb
second choice = RAILS_ROOT/app/views/general/some/shared/_view.html.erb
Good times.
module ActionController
class Base
alias_method :type, :controller_path
GENERAL_BASE = 'general'
def transform_template_path_with_type_override(template_path)
actual_template_path = template_path
if template_path.include?('/') && template_path_includes_controller?(template_path)
actual_template_path = strip_out_controller(template_path)
end
general_path = [GENERAL_BASE, actual_template_path].join('/')
type_path = general_path.split('/').insert(-2, '_types', type).join('/')
if block_given?
[type_path, general_path, template_path].each { |path| yield path }
else
{
:type => type_path,
:specific => type_path,
:general => general_path,
:template => template_path,
:original => template_path
}
end
end
end
end
module ActionView
class Base
GENERAL_BASE = 'general'
private
def template_exists_with_type_override?(template_path, extension)
controller.transform_template_path_with_type_override(template_path) do |tmp_path|
file_path = full_template_path(tmp_path, extension)
if @@method_names.has_key?(file_path) || FileTest.exists?(file_path)
template_path.replace tmp_path # this is a nasty trick to replace the input template path with the one we're going to be using
return true
end
end
false
end
alias_method_chain :template_exists?, :type_override
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment