Class: BeanSprout::SproutBunch
- Inherits:
-
Object
- Object
- BeanSprout::SproutBunch
- Includes:
- PackagePrivate::InternalClass
- Defined in:
- lib/bean_sprout/transaction.rb
Defined Under Namespace
Classes: IllegalStateError, NotBalancedError
Instance Attribute Summary collapse
-
#sprouts ⇒ Object
readonly
Returns the value of attribute sprouts.
Attributes included from PackagePrivate::InternalClass
Instance Method Summary collapse
- #balanced! ⇒ Object
- #balanced? ⇒ Boolean
-
#initialize(id, sprouts) ⇒ SproutBunch
constructor
A new instance of SproutBunch.
- #plant ⇒ Object
- #remove ⇒ Object
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
#sprouts ⇒ Object (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
33 34 35 |
# File 'lib/bean_sprout/transaction.rb', line 33 def balanced! raise NotBalancedError.new("#{@sprouts} not balanced.") unless balanced? end |
#balanced? ⇒ 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 |
#plant ⇒ Object
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 |
#remove ⇒ Object
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 |