6 use Test::More no_plan => 53;
22 BankAccount->meta->add_attribute('$:balance' => (
23 accessor => 'balance',
24 init_arg => 'balance',
28 sub new { (shift)->meta->new_object(@_) }
31 my ($self, $amount) = @_;
32 #warn "deposited $amount in $self";
33 $self->balance($self->balance + $amount);
37 my ($self, $amount) = @_;
38 my $current_balance = $self->balance();
39 ($current_balance >= $amount)
40 || confess "Account overdrawn";
41 #warn "withdrew $amount from $self";
42 $self->balance($current_balance - $amount);
45 package CheckingAccount;
50 use base 'BankAccount';
52 CheckingAccount->meta->add_attribute('$:overdraft_account' => (
53 accessor => 'overdraft_account',
54 init_arg => 'overdraft',
57 CheckingAccount->meta->add_before_method_modifier('withdraw' => sub {
58 my ($self, $amount) = @_;
59 #warn "hello from before";
60 my $overdraft_amount = $amount - $self->balance();
61 if ($overdraft_amount > 0) {
62 #warn "overdrawn $overdraft_amount";
63 $self->overdraft_account->withdraw($overdraft_amount);
64 $self->deposit($overdraft_amount);
66 #warn "balance after overdraft : " . $self->balance;
69 ::ok(CheckingAccount->meta->has_method('withdraw'), '... checking account now has a withdraw method');
73 my $savings_account = BankAccount->new(balance => 250);
74 isa_ok($savings_account, 'BankAccount');
76 is($savings_account->balance, 250, '... got the right savings balance');
78 $savings_account->withdraw(50);
79 } '... withdrew from savings successfully';
80 is($savings_account->balance, 200, '... got the right savings balance after withdrawl');
82 $savings_account->deposit(150);
83 is($savings_account->balance, 350, '... got the right savings balance after deposit');
85 my $checking_account = CheckingAccount->new(
87 overdraft => $savings_account
89 isa_ok($checking_account, 'CheckingAccount');
90 isa_ok($checking_account, 'BankAccount');
92 is($checking_account->overdraft_account, $savings_account, '... got the right overdraft account');
94 is($checking_account->balance, 100, '... got the right checkings balance');
97 $checking_account->withdraw(200);
98 } '... withdrew from checking successfully';
100 is($checking_account->balance, 0, '... got the right checkings balance after withdrawl');
101 is($savings_account->balance, 250, '... got the right savings balance after overdraft withdrawl');