Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Initializer to tweak auto-generation of partial_path based on rendering objects
# 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
You can’t perform that action at this time.