Commit | Line | Data |
66b226e5 |
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, |
648519ab |
10 | trigger => sub { shift->_record_balance(@_) }, |
66b226e5 |
11 | ); |
12 | |
13 | has owner => ( |
14 | is => 'rw', |
15 | isa => 'Person', |
16 | weak_ref => 1, |
17 | ); |
18 | |
19 | has 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 |
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 | |
648519ab |
44 | sub _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 | |
55 | no Moose; |
56 | |
57 | __PACKAGE__->meta->make_immutable; |
58 | |
59 | 1; |