シンプル::税とリアル::税の2つの役割があるとします。テスト環境では、Simple :: Taxを使いたいのですが、実務ではReal :: Taxを使いたいと思います。これを行う最善の方法は何ですか?私が最初に考えたのは異なる役割を持つオブジェクトを作成するために、new
方法の異なるバージョンを使用していた:Mooseでモーキングの役割を処理する方法は?
#!/usr/bin/perl
use warnings;
{
package Simple::Tax;
use Moose::Role;
requires 'price';
sub calculate_tax {
my $self = shift;
return int($self->price * 0.05);
}
}
{
package A;
use Moose;
use Moose::Util qw(apply_all_roles);
has price => (is => "rw", isa => 'Int'); #price in pennies
sub new_with_simple_tax {
my $class = shift;
my $obj = $class->new(@_);
apply_all_roles($obj, "Simple::Tax");
}
}
my $o = A->new_with_simple_tax(price => 100);
print $o->calculate_tax, " cents\n";
私の第二の考えは異なるwith
ステートメントを使用するためのパッケージの本体でif文を使用していた:
#!/usr/bin/perl
use warnings;
{
package Complex::Tax;
use Moose::Role;
requires 'price';
sub calculate_tax {
my $self = shift;
#pretend this is more complex
return int($self->price * 0.15);
}
}
{
package Simple::Tax;
use Moose::Role;
requires 'price';
sub calculate_tax {
my $self = shift;
return int($self->price * 0.05);
}
}
{
package A;
use Moose;
has price => (is => "rw", isa => 'Int'); #price in pennies
if ($ENV{TEST_A}) {
with "Simple::Tax";
} else {
with "Complex::Tax";
}
}
my $o = A->new(price => 100);
print $o->calculate_tax, " cents\n";
これらのうちの1つは他のものより優れていますか、どちらかについて恐ろしいものがありますか、まだ私が考えていないより良い方法があります。
したがって、単純な税の役割の 'around calculate_tax'メソッドは、実際にオブジェクトの' calculate_tax'メソッドを呼び出すことはありません。私はそれが一番クリーンな方法だと思う。 –
正確には、あなたはそれを置き換えるために 'around'を使って親メソッドを完全にオーバーライドします。 – perigrin