6 use Test::More tests => 20;
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 $self->balance($self->balance + $amount);
36 my ($self, $amount) = @_;
37 my $current_balance = $self->balance();
38 ($current_balance >= $amount)
39 || confess "Account overdrawn";
40 $self->balance($current_balance - $amount);
43 package CheckingAccount;
49 use base 'BankAccount';
51 CheckingAccount->meta->add_attribute('$:overdraft_account' => (
52 accessor => 'overdraft_account',
53 init_arg => 'overdraft',
56 CheckingAccount->meta->add_before_method_modifier('withdraw' => sub {
57 my ($self, $amount) = @_;
58 my $overdraft_amount = $amount - $self->balance();
59 if ($overdraft_amount > 0) {
60 $self->overdraft_account->withdraw($overdraft_amount);
61 $self->deposit($overdraft_amount);
65 ::ok(CheckingAccount->meta->has_method('withdraw'), '... checking account now has a withdraw method');
66 ::isa_ok(CheckingAccount->meta->get_method('withdraw'), 'Class::MOP::Method::Wrapped');
67 ::isa_ok(BankAccount->meta->get_method('withdraw'), 'Class::MOP::Method');
71 my $savings_account = BankAccount->new(balance => 250);
72 isa_ok($savings_account, 'BankAccount');
74 is($savings_account->balance, 250, '... got the right savings balance');
76 $savings_account->withdraw(50);
77 } '... withdrew from savings successfully';
78 is($savings_account->balance, 200, '... got the right savings balance after withdrawl');
80 $savings_account->withdraw(250);
81 } '... could not withdraw from savings successfully';
84 $savings_account->deposit(150);
85 is($savings_account->balance, 350, '... got the right savings balance after deposit');
87 my $checking_account = CheckingAccount->new(
89 overdraft => $savings_account
91 isa_ok($checking_account, 'CheckingAccount');
92 isa_ok($checking_account, 'BankAccount');
94 is($checking_account->overdraft_account, $savings_account, '... got the right overdraft account');
96 is($checking_account->balance, 100, '... got the right checkings balance');
99 $checking_account->withdraw(50);
100 } '... withdrew from checking successfully';
101 is($checking_account->balance, 50, '... got the right checkings balance after withdrawl');
102 is($savings_account->balance, 350, '... got the right savings balance after checking withdrawl (no overdraft)');
105 $checking_account->withdraw(200);
106 } '... withdrew from checking successfully';
107 is($checking_account->balance, 0, '... got the right checkings balance after withdrawl');
108 is($savings_account->balance, 200, '... got the right savings balance after overdraft withdrawl');