Rails宝典の第五十五式:ビューをきれいにする


Shopping Cartの例を見てみましょう.

Full Price: 
<% if line_item.unit_price == 0 %>
<td class="price">FREE</td>
<% else %>
<td class="price">
  <%= number_to_currency(line_item.unit_price*line_item.quantity) %>
</td>
<% end %>

<%
total = @cart.line_items.to_a.sum do |line_item|
  line_item.unit_price*line_item.quantity
end
%>
Total Price: <%= number_to_currency total %>

ビューには論理コードが多すぎて、とても見苦しいです.bad smell、私たちはこれらのコードを抽出して、Modelやhelperに書くべきです.

# models/line_item.rb
def full_price
  unit_price*quantity
end

# models/cart.rb
def total_price
  line_item.to_a.sum(&:full_price)
end

# helpers/carts_helper.rb
def free_when_zero(price)
  price.zero? ? "FREE" : number_to_currency(price)
end

これでページコードがきれいになります.

<!-- views/carts/show.rhtml -->
Full Price: 
<%= render: partial => 'line_item', :collection => @cart.line_items %>

Total:
<%= number_to_currency @cart.total_price %>

<!-- views/carts/_line_item.rhtml -->
<%= free_when_zero(line_item.full_price) %>