Guest User

Untitled

a guest
Feb 20th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. class Cart
  2. include Reloadable
  3.  
  4. attr_reader :items
  5.  
  6. def initialize
  7. @items = []
  8. end
  9.  
  10. def total_price
  11. @items.inject(0) { |sum, item| sum + item.price }
  12. end
  13.  
  14. def total_items
  15. @items.inject(0) { |sum, item| sum + item.quantity }
  16. end
  17.  
  18. def add_product(product)
  19. current_item = @items.find{|item| item.product == product}
  20. if current_item
  21. current_item.increment_quantity
  22. else
  23. current_item = CartItem.new(product)
  24. @items << current_item
  25. end
  26. current_item
  27. end
  28.  
  29. def remove_product(product)
  30. current_item = @items.find{|item| item.product == product}
  31. if current_item.quantity > 1
  32. current_item.quantity = current_item.quantity - 1
  33. elsif current_item.quantity == 1
  34. @items.delete(current_item)
  35. end
  36. current_item
  37. end
  38.  
  39. end
Add Comment
Please, Sign In to add comment