编程是我的爱好。

(十)-清空购物车和格式化金额

上一篇 / 下一篇  2007-09-16 06:55:10 / 个人分类:编程语言

在上次的内容里,我们给购物车添加了错误处理,这次来实现清空购物车和金额的格式化处理。

 

到现在我们还没有给显示购物信息列表页面的“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)

spri ntf("$%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>

现在可以看看最后的结果了,如图:



TAG: ruby

小飞猪之Ruby窝 引用 删除 drive2me   /   2007-09-17 08:05:28
好!
小飞猪之Ruby窝 引用 删除 drive2me   /   2007-09-17 08:05:26
5
 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2009-07-05  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 628
  • 日志数: 16
  • 建立时间: 2007-09-13
  • 更新时间: 2008-03-11

RSS订阅

Open Toolbar