exercises for section 6
[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,
10 trigger => sub { $_[0]->_record_difference( $_[1] ) },
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
25sub BUILD {
26 my $self = shift;
27
28 $self->_record_difference( $self->balance );
29}
30
31sub deposit {
32 my $self = shift;
33 my $amount = shift;
34
35 $self->balance( $self->balance + $amount );
36}
37
38sub withdraw {
39 my $self = shift;
40 my $amount = shift;
41
42 die "Balance cannot be negative"
43 if $self->balance < $amount;
44
45 $self->balance( $self->balance - $amount );
46}
47
48sub _record_difference {
49 my $self = shift;
50 my $new_value = shift;
51
52 my $old_value = sum @{ $self->history };
53
54 push @{ $self->history }, $new_value - ( $old_value || 0 );
55}
56
57no Moose;
58
59__PACKAGE__->meta->make_immutable;
60
611;