Fix up trigger instructions and example implementation.
[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 => (
ed84c5c6 20 traits => ['Array'],
66b226e5 21 is => 'ro',
22 isa => 'ArrayRef[Int]',
23 default => sub { [] },
ed84c5c6 24 handles => { add_history => 'push' },
66b226e5 25);
26
66b226e5 27sub deposit {
28 my $self = shift;
29 my $amount = shift;
30
31 $self->balance( $self->balance + $amount );
32}
33
34sub 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
648519ab 44sub _record_balance {
45 my $self = shift;
46 shift;
ed84c5c6 47
48 return unless @_;
49
648519ab 50 my $old_value = shift;
66b226e5 51
ed84c5c6 52 $self->add_history($old_value);
66b226e5 53}
54
55no Moose;
56
57__PACKAGE__->meta->make_immutable;
58
591;