Class: Transbank::Onepay::ShoppingCart

Inherits:
Object
  • Object
show all
Includes:
Utils::JSONUtils
Defined in:
lib/transbank/sdk/onepay/models/shopping_cart.rb

Overview

Represents a Shopping Cart, which contains [Item]s that the user wants to buy

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils::JSONUtils

included, #jsonify, #transform_hash_keys, #underscore

Constructor Details

#initialize(items = []) ⇒ ShoppingCart

if nil, an empty shopping cart is created

Parameters:

  • items (Array, nil) (defaults to: [])

    an array of Hashes that can be converted to [Item]



12
13
14
15
16
17
18
19
20
21
22
# 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

Instance Attribute Details

#itemsArray<Item> (readonly)

Returns An [Array<Item>] with the [ShoppingCart] contents.

Returns:

  • (Array<Item>)

    An [Array<Item>] with the [ShoppingCart] contents



8
9
10
# File 'lib/transbank/sdk/onepay/models/shopping_cart.rb', line 8

def items
  @items
end

Instance Method Details

#<<(item) ⇒ Object

Alias for #add



35
36
37
# File 'lib/transbank/sdk/onepay/models/shopping_cart.rb', line 35

def << item
  add item
end

#add(item) ⇒ boolean

Return true if item is successfully added

Parameters:

  • item (Item)

    an instance of [Item]

Returns:

  • (boolean)

    return true if item is successfully added



26
27
28
29
30
31
32
# 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_quantityObject

Sum the quantity of items in the cart



59
60
61
62
# 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) ⇒ Object

Remove an [Item] from self

Raises:

  • (ShoppingCartError)

    if item is not found



41
42
43
44
45
# 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_allObject

Clear the cart, setting @items to []



48
49
50
# File 'lib/transbank/sdk/onepay/models/shopping_cart.rb', line 48

def remove_all
  @items = []
end

#totalInteger

Returns The amount in CLP of the [Item]s included in the [ShoppingCart].

Returns:

  • (Integer)

    The amount in CLP of the [Item]s included in the [ShoppingCart]



53
54
55
56
# 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