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