Class: ShoppingCartSession::Cart
- Inherits:
-
Object
- Object
- ShoppingCartSession::Cart
- Defined in:
- lib/shopping_cart_session.rb
Instance Attribute Summary collapse
-
#items ⇒ Object
readonly
Returns the value of attribute items.
-
#total_price ⇒ Object
readonly
Returns the value of attribute total_price.
Instance Method Summary collapse
- #add(product, amount = 1) ⇒ Object
- #empty ⇒ Object
-
#initialize(session) ⇒ Cart
constructor
A new instance of Cart.
- #remove(product) ⇒ Object
Constructor Details
#initialize(session) ⇒ Cart
Returns a new instance of Cart.
8 9 10 11 12 13 14 15 16 17 |
# File 'lib/shopping_cart_session.rb', line 8 def initialize(session) @session = session @items = session.key?(:cart_items) ? deserialize_json_objects(session[:cart_items]) : [] @items = @items.map { |item| item["amount"] = item["amount"].to_i item["price"] = item["price"].to_f item } @total_price = @items.reduce(0) { |sum, item| sum + item["price"].to_f * item["amount"] } end |
Instance Attribute Details
#items ⇒ Object (readonly)
Returns the value of attribute items.
58 59 60 |
# File 'lib/shopping_cart_session.rb', line 58 def items @items end |
#total_price ⇒ Object (readonly)
Returns the value of attribute total_price.
58 59 60 |
# File 'lib/shopping_cart_session.rb', line 58 def total_price @total_price end |
Instance Method Details
#add(product, amount = 1) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/shopping_cart_session.rb', line 19 def add(product, amount = 1) @total_price += product["price"].to_f products = @items.select { |p| p["id"].to_s == product.id.to_s } if products.length > 0 then products.first["amount"] += 1 else @items.push({ :id => product.id, :name => product.name, :price => product.price, :amount => amount }) end update_session end |
#empty ⇒ Object
38 39 40 41 42 |
# File 'lib/shopping_cart_session.rb', line 38 def empty @session[:cart_items] = "" @items = [] @total_price = 0 end |
#remove(product) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/shopping_cart_session.rb', line 44 def remove(product) @total_price -= product["price"].to_f item = find_item(product) if item and item["amount"].to_i > 1 then item["amount"] -= 1 else @items = @items.reject { |item| item["id"].to_s == product["id"].to_s } end update_session end |