This episode starts off with a big, messy template. Watch as this code shrinks and becomes more readable while the interface stays the same.
<!-- views/carts/show.rhtml -->
<% title "Shopping Cart" %>
<table id="line_items">
<tr>
<th>Product</th>
<th>Qty</th>
<th class="price">Unit Price</th>
<th class="price">Full Price</th>
</tr>
<%= render :partial => 'line_item', :collection => @cart.line_items %>
<tr>
<td class="total price" colspan="4">
Total: <%= number_to_currency @cart.total_price %>
</td>
</tr>
</table>
<!-- views/carts/_line_item.rhtml -->
<tr class="<%= cycle :odd, :even %>">
<td><%=h line_item.product.name %></td>
<td class="qty"><%= line_item.quantity %></td>
<td class="price"><%= free_when_zero(line_item.unit_price) %></td>
<td class="price"><%= free_when_zero(line_item.full_price) %></td>
</tr>
# models/line_item.rb
def full_price
unit_price*quantity
end
# models/cart.rb
def total_price
line_items.to_a.sum(&:full_price)
end
# helpers/carts_helper.rb
def free_when_zero(price)
price.zero? ? "FREE" : number_to_currency(price)
end