simplify history recording task
[gitmo/moose-presentations.git] / moose-class / exercises / answers / 06-advanced-attributes / BankAccount.pm
CommitLineData
66b226e5 1package BankAccount;
2
3use List::Util qw( sum );
4use Moose;
5
6has balance => (
7 is => 'rw',
8 isa => 'Int',
9 default => 100,
648519ab 10 trigger => sub { shift->_record_balance(@_) },
66b226e5 11);
12
13has owner => (
14 is => 'rw',
15 isa => 'Person',
16 weak_ref => 1,
17);
18
19has history => (
20 is => 'ro',
21 isa => 'ArrayRef[Int]',
22 default => sub { [] },
23);
24
66b226e5 25sub deposit {
26 my $self = shift;
27 my $amount = shift;
28
29 $self->balance( $self->balance + $amount );
30}
31
32sub withdraw {
33 my $self = shift;
34 my $amount = shift;
35
36 die "Balance cannot be negative"
37 if $self->balance < $amount;
38
39 $self->balance( $self->balance - $amount );
40}
41
648519ab 42sub _record_balance {
43 my $self = shift;
44 shift;
45 my $old_value = shift;
66b226e5 46
648519ab 47 push @{ $self->history }, $old_value;
66b226e5 48}
49
50no Moose;
51
52__PACKAGE__->meta->make_immutable;
53
541;