6 use Test::More tests => 19;
20 BankAccount->meta->add_attribute('balance' => (
21 accessor => 'balance',
22 init_arg => 'balance',
26 sub new { (shift)->meta->new_object(@_) }
29 my ($self, $amount) = @_;
30 $self->balance($self->balance + $amount);
34 my ($self, $amount) = @_;
35 my $current_balance = $self->balance();
36 ($current_balance >= $amount)
37 || confess "Account overdrawn";
38 $self->balance($current_balance - $amount);
41 package CheckingAccount;
47 use base 'BankAccount';
49 CheckingAccount->meta->add_attribute('overdraft_account' => (
50 accessor => 'overdraft_account',
51 init_arg => 'overdraft',
54 CheckingAccount->meta->add_before_method_modifier('withdraw' => sub {
55 my ($self, $amount) = @_;
56 my $overdraft_amount = $amount - $self->balance();
57 if ($overdraft_amount > 0) {
58 $self->overdraft_account->withdraw($overdraft_amount);
59 $self->deposit($overdraft_amount);
63 ::ok(CheckingAccount->meta->has_method('withdraw'), '... checking account now has a withdraw method');
64 ::isa_ok(CheckingAccount->meta->get_method('withdraw'), 'Class::MOP::Method::Wrapped');
65 ::isa_ok(BankAccount->meta->get_method('withdraw'), 'Class::MOP::Method');
69 my $savings_account = BankAccount->new(balance => 250);
70 isa_ok($savings_account, 'BankAccount');
72 is($savings_account->balance, 250, '... got the right savings balance');
74 $savings_account->withdraw(50);
75 } '... withdrew from savings successfully';
76 is($savings_account->balance, 200, '... got the right savings balance after withdrawl');
78 $savings_account->withdraw(250);
79 } '... could not withdraw from savings successfully';
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(50);
98 } '... withdrew from checking successfully';
99 is($checking_account->balance, 50, '... got the right checkings balance after withdrawl');
100 is($savings_account->balance, 350, '... got the right savings balance after checking withdrawl (no overdraft)');
103 $checking_account->withdraw(200);
104 } '... withdrew from checking successfully';
105 is($checking_account->balance, 0, '... got the right checkings balance after withdrawl');
106 is($savings_account->balance, 200, '... got the right savings balance after overdraft withdrawl');