Class Cart
In: app/models/cart.rb
Parent: Object

A Cart consists of a list of LineItem objects and a current total price. Adding a product to the cart will either add a new entry to the list or increase the quantity of an existing item in the list. In both cases the total price will be updated.

Class Cart is a model, but does not represent information stored in the database. It therefore does not inherit from ActiveRecord::Base.

Methods

add_product   empty!   new  

Attributes

items  [R]  An array of LineItem objects
total_price  [R]  The total price of everything added to this cart

Public Class methods

Create a new shopping cart. Delegates this work to empty!

[Source]

    # File app/models/cart.rb, line 20
20:   def initialize
21:     empty!
22:   end

Public Instance methods

Add a product to our list of items. If an item already exists for that product, increase the quantity for that item rather than adding a new item.

[Source]

    # File app/models/cart.rb, line 27
27:   def add_product(product)
28:     item = @items.find {|i| i.product_id == product.id}
29:     if item
30:       item.quantity += 1
31:     else
32:       item = LineItem.for_product(product)
33:       @items << item
34:     end
35:     @total_price += product.price
36:   end

Empty the cart by resetting the list of items and zeroing the current total price.

[Source]

    # File app/models/cart.rb, line 40
40:   def empty!
41:     @items = []
42:     @total_price = 0.0
43:   end

[Validate]