Partial Path Customizer
Partial Path Customizer allows you to override #to_partial_path
for a Rails model at runtime.
Installation & Upgrading
This gem is a railtie and is meant to be used with Rails. It is tested with versions of Rails down to 3.2.
Partial Path Customizer is recommended to be run as a gem and included in your Gemfile:
“by gem ‘partial_path_customizer’
“
Helper
Partial path customizers provides a helper method to automatically set the partial path for the object you want to render. Here is how you would render an object normally.
“b <%= render @bike %>
“
This would render the bikes/bike
partial. Now if you want to customize the partial path, use the customize_partial_path
like this.
“b <%= render customize_partial_path(@bike, ‘summary’) %>
“
This renders the bikes/summary
partial instead. The partial path with this helper is generated by the object’s model_name pluralized.
Heterogenous collections
This is also very useful for rendering heterogenous collections with custom partial paths. For example, if you have this collection:
“by
Somewhere in the controller
@listings = [Bike.new, Wheelset.new, Bike.new]
“
and render it like this
“b <%= render @listings %>
“
it will render the partials bikes/bike
, wheelsets/wheels
, and bikes/bike
. If you would like the partial names to to be rendered like bikes/summary
, wheelsets/summary
, and bikes/summary
, you can do this
“b <%= render customize_partial_path(@listings, ‘summary’) %>
“
Customizing partial_path generation
If you need to further customize how the partial path is generated, you can pass a callable object in as the second argument. The callable object will receive a reference to the model when it’s #call method is called.
“by <%= render customize_partial_path(@bike, ->(model){ “#modelmodel.classmodel.class.model_namemodel.class.model_name.singular/#modelmodel.status_summary” })
“
That would allow you to generate a partial path like bike/sold_summary
.
Note: This is a low-level API and the higher level customize_object_partial_path(<object>, <partial_name>)
should be used in most cases.
License
Partial Path Customizer is Copyright © 2014 Animas Code Labs. It is free software, and may be redistributed under the terms specified in the LICENSE file.