is => 'rw',
isa => 'Int',
default => 100,
- trigger => sub { $_[0]->_record_difference( $_[1] ) },
+ trigger => sub { shift->_record_balance(@_) },
);
has owner => (
default => sub { [] },
);
-sub BUILD {
- my $self = shift;
-
- $self->_record_difference( $self->balance );
-}
-
sub deposit {
my $self = shift;
my $amount = shift;
$self->balance( $self->balance - $amount );
}
-sub _record_difference {
- my $self = shift;
- my $new_value = shift;
-
- my $old_value = sum @{ $self->history };
+sub _record_balance {
+ my $self = shift;
+ shift;
+ my $old_value = shift;
- push @{ $self->history }, $new_value - ( $old_value || 0 );
+ push @{ $self->history }, $old_value;
}
no Moose;
# Finally, add a read-only history attribute. This will be an ArrayRef
# of Int's. This should default to an empty array reference.
#
-# Use a trigger to record the _difference_ after each change to the
-# balance. The previous balance is the sum of all the previous
-# changes. You can use List::Util's sum function to calculate this. To
-# avoid warnings the first time history is recorded, default to 0 if
-# history is empty.
+# Use a trigger to record the _old value_ of the balance each time it
+# changes.
#
# Use a BUILD method in BankAccount to record the original balance in
# the history.
'owner of bank account is person that created account' );
$person->deposit(10);
- is_deeply( $person->account->history, [ 100, 10 ],
+ is_deeply( $person->account->history, [ 100 ],
'deposit was recorded in account history' );
$person->withdraw(15);
- is_deeply( $person->account->history, [ 100, 10, -15 ],
+ is_deeply( $person->account->history, [ 100, 110 ],
+ 'withdrawal was recorded in account history' );
+
+ $person->withdraw(45);
+ is_deeply( $person->account->history, [ 100, 110, 95 ],
'withdrawal was recorded in account history' );
}