4 use Test::More tests => 19;
18 BankAccount->meta->add_attribute('balance' => (
19 accessor => 'balance',
20 init_arg => 'balance',
24 sub new { (shift)->meta->new_object(@_) }
27 my ($self, $amount) = @_;
28 $self->balance($self->balance + $amount);
32 my ($self, $amount) = @_;
33 my $current_balance = $self->balance();
34 ($current_balance >= $amount)
35 || confess "Account overdrawn";
36 $self->balance($current_balance - $amount);
39 package CheckingAccount;
45 use base 'BankAccount';
47 CheckingAccount->meta->add_attribute('overdraft_account' => (
48 accessor => 'overdraft_account',
49 init_arg => 'overdraft',
52 CheckingAccount->meta->add_before_method_modifier('withdraw' => sub {
53 my ($self, $amount) = @_;
54 my $overdraft_amount = $amount - $self->balance();
55 if ($overdraft_amount > 0) {
56 $self->overdraft_account->withdraw($overdraft_amount);
57 $self->deposit($overdraft_amount);
61 ::ok(CheckingAccount->meta->has_method('withdraw'), '... checking account now has a withdraw method');
62 ::isa_ok(CheckingAccount->meta->get_method('withdraw'), 'Class::MOP::Method::Wrapped');
63 ::isa_ok(BankAccount->meta->get_method('withdraw'), 'Class::MOP::Method');
67 my $savings_account = BankAccount->new(balance => 250);
68 isa_ok($savings_account, 'BankAccount');
70 is($savings_account->balance, 250, '... got the right savings balance');
72 $savings_account->withdraw(50);
73 } '... withdrew from savings successfully';
74 is($savings_account->balance, 200, '... got the right savings balance after withdrawl');
76 $savings_account->withdraw(250);
77 } '... could not withdraw from savings successfully';
80 $savings_account->deposit(150);
81 is($savings_account->balance, 350, '... got the right savings balance after deposit');
83 my $checking_account = CheckingAccount->new(
85 overdraft => $savings_account
87 isa_ok($checking_account, 'CheckingAccount');
88 isa_ok($checking_account, 'BankAccount');
90 is($checking_account->overdraft_account, $savings_account, '... got the right overdraft account');
92 is($checking_account->balance, 100, '... got the right checkings balance');
95 $checking_account->withdraw(50);
96 } '... withdrew from checking successfully';
97 is($checking_account->balance, 50, '... got the right checkings balance after withdrawl');
98 is($savings_account->balance, 350, '... got the right savings balance after checking withdrawl (no overdraft)');
101 $checking_account->withdraw(200);
102 } '... withdrew from checking successfully';
103 is($checking_account->balance, 0, '... got the right checkings balance after withdrawl');
104 is($savings_account->balance, 200, '... got the right savings balance after overdraft withdrawl');