Class: Effective::Cart
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- Effective::Cart
- Defined in:
- app/models/effective/cart.rb
Instance Method Summary collapse
- #add(item, quantity: 1) ⇒ Object (also: #add_to_cart)
- #empty? ⇒ Boolean
- #find(item) ⇒ Object
- #includes?(item) ⇒ Boolean
- #remove(obj) ⇒ Object (also: #remove_from_cart)
- #size ⇒ Object
- #subtotal ⇒ Object (also: #total)
Instance Method Details
#add(item, quantity: 1) ⇒ Object Also known as: add_to_cart
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'app/models/effective/cart.rb', line 14 def add(item, quantity: 1) raise 'expecting an acts_as_purchasable object' unless item.kind_of?(ActsAsPurchasable) existing_item = cart_items.where(purchasable_id: item.id, purchasable_type: item.class.name).first if item.quantity_enabled? && (quantity + (existing_item.quantity rescue 0)) > item.quantity_remaining raise EffectiveOrders::SoldOutException, "#{item.title} is sold out" return end if existing_item.present? existing_item.update_attributes(quantity: existing_item.quantity + quantity) else cart_items.create(cart: self, purchasable_id: item.id, purchasable_type: item.class.name, quantity: quantity) end end |
#empty? ⇒ Boolean
49 50 51 |
# File 'app/models/effective/cart.rb', line 49 def empty? size == 0 end |
#find(item) ⇒ Object
41 42 43 |
# File 'app/models/effective/cart.rb', line 41 def find(item) cart_items.to_a.find { |cart_item| cart_item == item || cart_item.purchasable == item } end |
#includes?(item) ⇒ Boolean
37 38 39 |
# File 'app/models/effective/cart.rb', line 37 def includes?(item) find(item).present? end |
#remove(obj) ⇒ Object Also known as: remove_from_cart
32 33 34 |
# File 'app/models/effective/cart.rb', line 32 def remove(obj) (cart_items.find(cart_item) || cart_item).try(:destroy) end |
#size ⇒ Object
45 46 47 |
# File 'app/models/effective/cart.rb', line 45 def size cart_items.size end |
#subtotal ⇒ Object Also known as: total
53 54 55 |
# File 'app/models/effective/cart.rb', line 53 def subtotal cart_items.map { |ci| ci.subtotal }.sum end |