File: app/models/cart.rb

Overview
Module Structure
Class Hierarchy
Code

Overview

Module Structure

  module: <Toplevel Module>
  class: Cart#9
inherits from
  Object ( Builtin-Module )
has properties
attribute: items [R] #10
method: initialize #12
method: add_product / 1 #17
method: total_price #30
method: total_items #36

Class Hierarchy

Object ( Builtin-Module )
  Cart    #9

Code

   1  #---
   2  # Excerpted from "Agile Web Development with Rails, 3rd Ed.",
   3  # published by The Pragmatic Bookshelf.
   4  # Copyrights apply to this code. It may not be used to create training material, 
   5  # courses, books, articles, and the like. Contact us if you are in doubt.
   6  # We make no guarantees that this code is fit for any purpose. 
   7  # Visit http://www.pragmaticprogrammer.com/titles/rails3 for more book information.
   8  #---
   9  class Cart
  10    attr_reader :items   
  11    
  12    def initialize
  13      @items = []
  14    end
  15    
  16    
  17    def add_product(product)
  18      current_item = @items.find {|item| item.product == product}
  19      if current_item
  20        current_item.increment_quantity
  21      else
  22        current_item = CartItem.new(product)
  23        @items << current_item 
  24      end
  25      current_item
  26    end
  27    
  28 
  29    
  30    def total_price
  31      @items.sum { |item| item.price }
  32    end
  33    
  34 
  35    
  36    def total_items
  37      @items.sum { |item| item.quantity }
  38    end
  39    
  40  end