Question

I have a TripDecorator which decorates a Trip object. A Trip has many Activities.

I'd like to create a TripDecorator method that generates a list of activities belonging to a specific Trip.

How can I convert this:

<h5>Activities</h5>
<ul>
<% @trip.activities.each do |activity| %>
  <%= content_tag :li, activity.name %>
<% end %>
</ul>

to this:

<%= @trip.activities_list %>

I'd like nothing to appear if no activities exist. Is this abstraction possible with Draper?

Was it helpful?

Solution

Sure, this is trivial.

class TripDecorator
  decorates :trip

  def activities_list
    return if activities.empty?
    h.content_tag(:h5, "Activities") +
    h.content_tag(:ul) do
      activities.map do |activity|
        h.content_tag(:li, activity.name)
      end.join
    end.html_safe
  end
end

You just end up concatenating content_tag calls to generate your markup, and you can short-circuit the method if there aren't any activities to loop over.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top