您的位置:首页 > 编程语言 > Ruby

Ruby on rails开发从头来(windows)(十)-清空购物车和格式化金额

2011-08-08 14:53 561 查看
在上次的内容里,我们给购物车添加了错误处理,这次来实现清空购物车和金额的格式化处理。

 

到现在我们还没有给显示购物信息列表页面的“empty cart”链接添加任何处理。我们首先来实现这个功能:
1.       在Store_Control.rb文件中添加empty_cart方法:
def empty_cart
find_cart.empty!
flash[:notice] = 'Your cart is now empty'
redirect_to(:action => 'index')
end
2.       接下来是cart.rb文件,添加下面的代码:
def empty!
      @items = []
      @total_price = 0.0
end
好了,就是这么简单,现在点击empty cart链接,会重新定位到index页面,并且显示一个消息,如图:



 
嗯,到这里你肯定看到store_controller中关于显示异常信息的flash的操作部分有重复代码,这是代码的坏味道,现在我们使用Extract Method,将这些代码提取到一个方法中,下面是修改后的代码,我们修改了add_to_cart,display_cart,empty_cart三个方法,并且添加了一个redirect_to_index方法:
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@cart.add_product(product)
redirect_to(:action => 'display_cart')
rescue
logger.error("Attempt to access invalid product #{params[:id]}")
flash[:notice] = 'Invalid product'
redirect_to_index('Invalid product')
end
 
def display_cart
@cart = find_cart
@items = @cart.items
if @items.empty?
redirect_to_index("Your cart is currently empty")
end
end
 
def empty_cart
find_cart.empty!
redirect_to_index('Your cart is now empty')
end
 
def redirect_to_index(msg = null)
flash[:notice] = msg
redirect_to(:action => 'index')
end
另外,cart.rb里也有重复的代码,我们重构一下:
def empty!
@items = []
@total_price = 0.0
end
 
def initialize
empty!
end
 
整理完了代码,再来看看另一个小功能,格式化金额:
1.       在rails_apps\depot\app\helpers目录下的application_helper.rb中添加代码:
def fmt_dollars(amt)
sprintf("$%0.2f", amt)
end
2.       修改rails_apps\depot\app\views\store目录下的display_cart.rhtml文件中的两行:
<td align="right"><%= item.unit_price %></td>
<td align="right"><%= item.unit_price * item.quantity %></td>

<td id="totalcell"><%= (@cart.total_price)%></td>
变为
<td align="right"><%= fmt_dollars(item.unit_price) %></td>
<td align="right"><%= fmt_dollars(item.unit_price * item.quantity) %></td>

<td id="totalcell"><%= fmt_dollars(@cart.total_price)%></td>
现在可以看看最后的结果了,如图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐