Ian,
The constructor arguments are not passed on via handles, only the
attributes themselves are handled in the constructor. You need to
handle the 'score' param in the BUILD method manually.
This would however, make a nice MooseX:: module.
- Stevan
On Oct 20, 2008, at 2:27 PM, Ian Sillitoe wrote:
I'm sure there's probably a simple answer to the following, however
I've got
to the point where I could really do with some advice.
I've abstracted the problem as much as possible to the code appended
below.
The "score" attribute only seems to be set after $c->score( $score )
has
been explicitly called rather than after initialisation through
MyClass->new( score => $score ).
I get the impression that the issue is probably related, if not the
same, as
one mentioned in a previous post ("bug / feature / idiot user?"
http://thread.gmane.org/gmane.comp.lang.perl.moose/319/focus=325).
i.e. it
comes down to the sequence of events involved in creating objects and
registering "handles" (if I understood that correctly). However, if
it is
the same, then I'm afraid I didn't really get what the suggested best
solution is: should I hack the BUILD process, rethink the way I'm
dealing
with Roles or just RTFM (I think I've done the latter, but I could
well be
wrong...)?
Many thanks in advance,
Ian
% cat test.pl
#!/usr/bin/perl -w
use MyClass;
my $c = MyClass->new( score => '75' );
# provided by...
warn $c->score; # undef [Role::HasComparisonResult]
warn $c->normalised_score; # 0 [MyClass::Result]
$c->score( 75 );
warn $c->score; # 75 [Role::HasComparisonResult]
warn $c->normalised_score; # 0.75 [MyClass::Result]
% cat MyClass.pm
package MyClass;
use Moose;
use MyClass::Result;
has 'result' => (
is => 'rw',
isa => 'MyClass::Result',
handles => [qw( query match score normalised_score )],
default => sub { MyClass::Result->new() },
);
1;
% cat MyClass/Result.pm
package MyClass::Result;
use Moose;
with 'Role::HasComparisonResult';
sub normalised_score { (shift)->score / 100 }
1;
% cat Role/HasComparisonResult.pm
package Role::HasComparisonResult;
use Moose::Role;
has 'match' => ( is => 'rw' );
has 'query' => ( is => 'rw' );
has 'score' => ( is => 'rw' );
1;
Directory:
test.pl
MyClass.pm
MyClass/Result.pm
Role/HasComparisonResult.pm
--
Dr Ian Sillitoe
CATH Team -- http://cathdb.info
"Advice is what we ask for when we already know
the answer but wish we didn't" -- Erica Jong