Created
May 11, 2011 16:48
-
-
Save obie/966850 to your computer and use it in GitHub Desktop.
Initializer to tweak auto-generation of partial_path based on rendering objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/partial_path_override.rb | |
# Override possibly undesirable naming convention used by Rails to automatically determine | |
# the path to partial templates when you pass model objects to the render method | |
# by Obie Fernandez http://blog.obiefernandez.com/content/2011/05/rending-collections-of-heterogeneous-objects-in-rails-1.html | |
ActionView::Partials::PartialRenderer.class_eval do | |
private | |
def partial_path(object = @object) | |
@partial_names[object.class.name] ||= begin | |
object = object.to_model if object.respond_to?(:to_model) | |
object.class.model_name.partial_path.dup.tap do |partial| | |
# I chose to limit this hack to events objects in my app's activity stream | |
if partial.include?("_events") | |
# Example: turns "nomination_events/nomination_event" into "events/nomination_event" | |
# More importantly, don't prepend the controller path so that this feature can | |
# be used across namespaces and controllers | |
partial.gsub!(/\A\w+_/,'') | |
else | |
path = @view.controller_path | |
partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment