Rendering collections with custom partial paths

283 views
Skip to first unread message

Alexander Kurakin

unread,
Feb 3, 2013, 5:11:47 AM2/3/13
to rubyonra...@googlegroups.com
Good day!

Sometimes we want just to render a collection:

render partial: collection: @cars

Sometimes we want to render a collection using custom partial name:

render partial: 'car_short', collection: @cars

Ok but if Car has has STI-subclasses we should write

class Car < ActiveRecord::Base; def to_partial_path(); "cars/#{kind}"; end; end
render collection: @cars

But wait! Partial will be 'cars/bmw', 'cars/mercedes'. But sometimes I want to render
a collection with '_short' postfix. But sometimes without it. But 'to_partial_path' is common...

What to do? This brief article, 4) Custom partial paths, says to do

@cars.each do |car|
  render partial: "cars/#{car.kind}_short", locals: { car: car }
end

But this code is... I don't like to do so, do you?

What about new 'render''s option? A 'postfix'/'prefix' options are nice for this example but...

Another example. Partial name is related to your role for this object ('owner', 'admin', etc.):

@cars.each do |car|
  render partial: "#{car.to_partial_path}_#{your_role_for(car)}", locals: { car: car }
end

What do you think? Is it a good idea? Thanx.

Alexander Kurakin

unread,
Feb 3, 2013, 5:17:41 AM2/3/13
to rubyonra...@googlegroups.com
The idea is to make an ability to give a Proc to 'partial' option. It will be yielded with 'object' argument:

render partial: -> { |car| "#{car.to_partial_path}_#{your_role_for(car)}" }, collection: @cars

It's backward compatibility...
Reply all
Reply to author
Forward
0 new messages