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


     

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

     

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

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


  • 相关阅读:
    python 第三方库大全
    windows CMD实现的信息收集工具
    ip协议是哪一层的协议
    MetaWeblog访问地址
    通过卸载程序触发恶意进程
    IP地址查询接口
    mysql 密码忘记解决办法
    查询IP地址的免费API
    showdan
    【译】android的审计和hacking工具
  • 原文地址:https://www.cnblogs.com/dahuzizyd/p/Ruby_Rails_Windows_dotnet_10.html
Copyright © 2020-2023  润新知