class Transbank::Onepay::ShoppingCart
Represents a Shopping Cart, which contains [Item]s that the user wants to buy
Attributes
items[R]
@return [Array<Item>] An [Array<Item>] with the [ShoppingCart] contents
Public Class Methods
new(items = [])
click to toggle source
@param items [Array, nil] an array of Hashes that can be converted to [Item] if nil, an empty shopping cart is created
# File lib/transbank/sdk/onepay/models/shopping_cart.rb, line 12 def initialize(items = []) # An [Array<Item>] with the [ShoppingCart] contents @items = [] return if items.nil? || items.empty? items.each do |it| it = transform_hash_keys it item = Item.new it self << item end end
Public Instance Methods
<<(item)
click to toggle source
Alias for add
# File lib/transbank/sdk/onepay/models/shopping_cart.rb, line 35 def << item add item end
add(item)
click to toggle source
@param item [Item] an instance of [Item] @return [boolean] return true if item is successfully added
# File lib/transbank/sdk/onepay/models/shopping_cart.rb, line 26 def add(item) new_total = total + item.total if new_total < 0 raise Errors::ShoppingCartError, "Total amount cannot be less than zero." end @items << item end
items_quantity()
click to toggle source
Sum the quantity of items in the cart
# File lib/transbank/sdk/onepay/models/shopping_cart.rb, line 59 def items_quantity # Array#sum is Ruby 2.4+ @items.reduce(0) { |total, item| total + item.quantity } end
remove(item)
click to toggle source
Remove an [Item] from self @raise [ShoppingCartError] if item is not found
# File lib/transbank/sdk/onepay/models/shopping_cart.rb, line 41 def remove(item) if @items.delete(item).nil? raise Errors::ShoppingCartError, "Item not found" end end
remove_all()
click to toggle source
Clear the cart, setting @items to []
# File lib/transbank/sdk/onepay/models/shopping_cart.rb, line 48 def remove_all @items = [] end
total()
click to toggle source
@return [Integer] The amount in CLP of the [Item]s included in the [ShoppingCart]
# File lib/transbank/sdk/onepay/models/shopping_cart.rb, line 53 def total # Array#sum is Ruby 2.4+ @items.reduce(0) { |total, item| total + item.total } end