ついに加法
やったこと
- Bankクラスの仮実装
- plusメソッドの追加
RubyとPythonでやったときはExpressionインタフェースを作ったのですが、今回今のところインタフェースが必要とは思えないので、作ってません。
lib/Money.pm
package Money; use strict; use warnings; use Carp; use version; our $VERSION = qv('0.0.3'); use overload ( "==" => \&equals, "eq" => \&equals, "!=" => \¬_equals, "ne" => \¬_equals, '""' => \&string, '*' => \×, '+' => \&plus, ); sub new { my ($class, $opts) =(@_); croak 'Not exists amount option' if not exists $opts->{amount}; croak 'Not exists currency option' if not exists $opts->{currency}; return bless $opts, $class; } sub equals { my ($self, $money) = (@_); use Test::More; return $self->amount == $money->amount && $self->currency eq $money->currency; } sub not_equals { my ($self, $money) = (@_); return not $self->equals($money); } sub string { my ($self) = (@_); return $self->amount . ' (' . __PACKAGE__ . ')'; } sub times { my ($self, $multiplier) = (@_); return Money->new({ amount => $self->amount * $multiplier, currency => $self->currency, }); } sub plus { my ($self, $addend) = (@_); return Money->new({ amount => $self->amount + $addend->amount, currency => $self->currency, }); } sub dollar { my ($class, $opts) =(@_); $opts->{currency} = 'USD'; return Money->new($opts); } sub franc { my ($class, $opts) =(@_); $opts->{currency} = 'CHF'; return Money->new($opts); } sub currency { my $self = shift; return $self->{currency}; } sub amount { my $self = shift; return $self->{amount}; } 1; package Bank; sub new { my ($class) =(@_); return bless {}, $class; } sub reduce { my ($self, $source, $to) = (@_); return Money->dollar({ amount => 10, }); } 1;
t/00money.t
use strict; use warnings; use Test::Class; Test::Class->runtests; package TestMoney; use strict; use warnings; use base 'Test::Class'; use Money; use Test::More; sub test_multiplication : Test(2) { my $five = Money->dollar({amount => 5}); is($five * 2, Money->dollar({amount => 10})); is($five * 3, Money->dollar({amount => 15})); } sub test_equality : Test(5) { ok(Money->dollar({amount => 5}) == Money->dollar({amount => 5})); ok(Money->dollar({amount => 5}) != Money->dollar({amount => 6})); ok(Money->franc ({amount => 5}) != Money->dollar({amount => 5})); } sub test_currency : Test(2) { is(Money->dollar({amount => 1})->currency, 'USD'); is(Money->franc ({amount => 1})->currency, 'CHF'); } sub test_simple_addition : Test(1) { my $sum = Money->dollar({amount =>5}) + Money->dollar({amount => 5}); my $bank = Bank->new; my $reduced = $bank->reduce($sum, 'USD'); is($reduced, Money->dollar({amount =>10})); } 1;