Rails宝典之第五十五式: 让视图干净些

本文介绍了一个具体的购物车示例,并展示了如何将复杂的视图逻辑移至Model和Helper中,以提高代码的整洁度和可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看一个Shopping Cart的例子:
[code]
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 %>
[/code]
视图中嵌入太多的逻辑代码,非常难看,bad smell,我们应该将将这些代码提取出来,写在Model或helper里:
[code]
# 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
[/code]
这样页面代码就干净多了:
[code]
<!-- 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) %>
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值