나는 두 가지 역할을한다고 말한다 : Simple :: Tax와 Real :: Tax. 테스트 환경에서는 Simple :: Tax를 사용하고 제작시 Real :: Tax를 사용하려고합니다. 이 작업을 수행하는 가장 좋은 방법은 무엇입니까?Moose에서 모의 역할을 처리하는 방법은 무엇입니까?
#!/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";
:
#!/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
문을 사용하는 경우를 사용했다 : 내 첫번째 생각은 다른 역할을 가진 개체를 만들 수 new
방법의 다른 버전을 사용하는 것이 었습니다
이 중 하나가 다른 것보다 좋으며, 둘 중 하나에 대해 끔찍한 점이 있으며 아직 생각하지 못한 더 나은 방법이 있습니다.
그래서 간단한 세금 역할의'around calculate_tax' 메소드는 실제로 객체에 대해'calculate_tax' 메소드를 호출하지 않습니다. 맞습니까? 나는 이것이 가장 깨끗한 방법이라고 생각한다. –
정확하게, 'around'를 사용하여 부모 메소드를 완전히 대체합니다. – perigrin