Subject: | Native Traits and Coercion |
In the attachment you see a simple "Person" class that i build with
primary 2 attributes and a self build subtype. The subtype "MyURI" that
needs to be a "URI" class with Coercion from a string.
When i set it to the "url" attribute then everything works like expected.
But when i try to add it with "add_bookmark" then the type failed with
the error message.
Show quoted text
> Method 'url' returned a URI object
> Value http://www.heise.de did not pass container type constraint
> 'MyURI' at /home/sidburn/perl510/lib/site_perl/5.10.1/Moose
> /Meta/Attribute/Native/MethodProvider/Array.pm line 129
>
Moose::Meta::Attribute::Native::MethodProvider::Array::__ANON__('Person=HASH(0x9b7a8c8)',
'http://www.heise.de') called at /home/sidburn/perl510/lib/site_perl
Show quoted text> /5.10.1/Moose/Meta/Attribute/Native/Trait.pm line 127
> Person::add_bookmark('Person=HASH(0x9b7a8c8)',
> 'http://www.heise.de') called at ./coerce.pl line 49
It seems that when i do "add_bookmark" the type "ArrayRef[MyURI]" works
that it only accepts the "MyURI" type, but the coercion from Str does
not get applied.
Subject: | coerce.pl |
#!/usr/bin/env perl
# Core Modules
use strict;
use warnings;
use utf8;
{
package Person;
use Moose;
use Moose::Util::TypeConstraints;
use URI;
subtype 'MyURI',
as 'Object',
where { $_->isa('URI') };
coerce 'MyURI',
from 'Str',
via { URI->new($_) };
has 'url' => (
is => 'rw',
isa => 'MyURI',
coerce => 1,
);
has 'bookmarks' => (
traits => ['Array'],
is => 'ro',
isa => 'ArrayRef[MyURI]',
default => sub { [] },
coerce => 1,
handles => {
add_bookmark => 'push',
},
);
}
my $you = Person->new;
$you->url('http://www.heise.de');
if ( $you->url->isa('URI') ) {
print "Method 'url' returned a URI object\n"
}
else {
print "Method 'url' is not an URI Object\n"
}
$you->add_bookmark('http://www.heise.de');