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) %>

你可能感兴趣的:(嵌入式,Rails,idea)