Class: BeanSprout::SproutBunch

Inherits:
Object
  • Object
show all
Includes:
PackagePrivate::InternalClass
Defined in:
lib/bean_sprout/transaction.rb

Defined Under Namespace

Classes: IllegalStateError, NotBalancedError

Instance Attribute Summary collapse

Attributes included from PackagePrivate::InternalClass

#public_interface

Instance Method Summary collapse

Methods included from PackagePrivate::InternalClass

#bind_public_interface, included

Constructor Details

#initialize(id, sprouts) ⇒ SproutBunch

Returns a new instance of SproutBunch.



17
18
19
20
# File 'lib/bean_sprout/transaction.rb', line 17

def initialize id, sprouts
  @id = id
  @sprouts = sprouts
end

Instance Attribute Details

#sproutsObject (readonly)

Returns the value of attribute sprouts.



7
8
9
# File 'lib/bean_sprout/transaction.rb', line 7

def sprouts
  @sprouts
end

Instance Method Details

#balanced!Object

Raises:



33
34
35
# File 'lib/bean_sprout/transaction.rb', line 33

def balanced!
  raise NotBalancedError.new("#{@sprouts} not balanced.") unless balanced?
end

#balanced?Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
29
30
31
# File 'lib/bean_sprout/transaction.rb', line 22

def balanced?
  balances = Hash.new(0)
  @sprouts.each do |sprout|
    currency = sprout.bean.currency
    balances[currency] += sprout.amount
  end
  balances.values.inject(true) do |acc, currency_balance|
    acc && currency_balance == 0
  end
end

#plantObject

Raises:



37
38
39
40
41
42
43
44
# File 'lib/bean_sprout/transaction.rb', line 37

def plant
  balanced!
  raise IllegalStateError, "Can't plant twice." if @in_place
  sprouts.each do |sprout|
    sprout.bean.grow sprout
  end
  @in_place = true
end

#removeObject

Raises:



46
47
48
49
50
51
52
53
# File 'lib/bean_sprout/transaction.rb', line 46

def remove
  balanced!
  raise IllegalStateError, "Must plant before remove." unless @in_place
  sprouts.each do |sprout|
    sprout.bean.pick sprout
  end
  @in_place = false
end