Class: Cart

Inherits:
Object
  • Object
show all
Defined in:
lib/cart.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCart

Returns a new instance of Cart.



4
5
6
# File 'lib/cart.rb', line 4

def initialize
  @cart_items = []
end

Instance Attribute Details

#cart_itemsObject (readonly)

Returns the value of attribute cart_items.



2
3
4
# File 'lib/cart.rb', line 2

def cart_items
  @cart_items
end

Instance Method Details

#add_item(item) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/cart.rb', line 8

def add_item(item)
  cart_item = find_item(item)
  if !cart_item.nil?
    cart_item.increment_quantity
  else
    @cart_items << CartItem.new(item)
  end
end

#empty?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/cart.rb', line 51

def empty?
  self.total_items.zero?
end

#find_item(item) ⇒ Object



21
22
23
# File 'lib/cart.rb', line 21

def find_item(item)
  @cart_items.find {|cart_item| cart_item.item.id == item.id }
end

#itemsObject



17
18
19
# File 'lib/cart.rb', line 17

def items
  @cart_items.map(&:item)
end

#items_for_paypalObject



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/cart.rb', line 55

def items_for_paypal
  @cart_items.collect do |cart_item|
    item = cart_item.item

    {
      :name => item.name,
      :quantity => cart_item.quantity,
      :amount => cart_item.to_cents,
    }
  end
end

#remove_item(item) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/cart.rb', line 37

def remove_item(item)
  cart_item = find_item(item)
  if cart_item.quantity > 1
    cart_item.decrease_quantity
  else
    @cart_items.delete_if {|ci| ci == cart_item}
  end
end

#remove_item!(item) ⇒ Object



46
47
48
49
# File 'lib/cart.rb', line 46

def remove_item!(item)
  cart_item = find_item(item)
  @cart_items.delete_if { |ci| ci == cart_item }
end

#totalObject



25
26
27
28
29
30
31
# File 'lib/cart.rb', line 25

def total
  total = 0.0
  @cart_items.each do |cart_item|
    total += (cart_item.item.price * cart_item.quantity)
  end
  total
end

#total_itemsObject



33
34
35
# File 'lib/cart.rb', line 33

def total_items
  @cart_items.map(&:quantity).inject{|sum, q| sum + q}.to_i
end