原创作者: hideto   阅读:1295次   评论:0条   更新时间:2011-05-26    
看一个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) %>
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics