views:

194

answers:

1

This is probably very easy, but I'm having a hard time figuring it out.

I have a partial:

<% for room in @scrape %>
<tr id="page_<%= room.id %>">
    <th scope="row" class="<%= cycle("spec", "specalt") -%>"><%=h room.name %></td>
    <td class="<%=current_cycle%>"><%=h room.day1 %></td>
    <td class="<%=current_cycle%>"><%=h room.day2 %></td>
    <td class="<%=current_cycle%>"><%=h room.day3 %></td>
    <td class="<%=current_cycle%>"><%=h room.day4 %></td>
    <td class="<%=current_cycle%>"><%=h room.day5 %></td>
    <td class="<%=current_cycle%>"><%=h room.day6 %></td>
    <td class="<%=current_cycle%>"><%=h room.day7 %></td>
    <td class="<%=current_cycle%>"><%= select_tag("room[#{room.id}]", options_for_select(0..room.spots,0)) %></td>

</tr>
<% end %>

From a find_by_sql result like so:

    ID         Room     Day1     Day2   Day3    Day4    Day5    Day6    Day7
   18298   Blue Room   13.23    13.23   13.23   13.23   13.23   13.23   13.23

But I don't know how many days there will be, how can I loop thru the column results for the different Days?

+5  A: 

This could be done in a helper using block/yield, but that's outside the scope of your question. I'll get right to the question by doing this inside the partial.

<% room.attributes.each do |key, value| %>
  <% if key.to_s.include?("day") %>
    <td class="<%=current_cycle%>"><%=h value.to_s %></td>
  <% end %>
<% end %>

Update: Here is the helper example. If this pattern is showing up more than once in your app, I think this is both more maintainable and readable.

def attributes_for(model, match, &block)
  model.attributes.each do |key, value|
    if key.to_s.include?(match)
      # we pass key and value in this example. but you can
      # pass whatever you want to the block.
      concat(capture(key, value, &block))
    end
  end
end

And this is now your partial:

<% attributes_for(room, "day") do |key, value| %>
  <td class="<%=current_cycle%>"><%=h value.to_s %></td>
<% end %>

More total lines of code, but better if you are going to be doing this throughout your app.

Walt Gordon Jones
beautiful... is this something that should be in a helper? not in the partial?
holden
If you are going to use this pattern in multiple places, then yes I would extract it into a helper. That's more DRY and a little more readable. I'll add the code in a few minutes.
Walt Gordon Jones
This is awesome. Thank you!
holden