我创建了子类型 Birth_d
如下所示,我试图将它与内置 Maybe
结合使用。类型,每 Moose::Manual::Types .
我收到错误 You cannot coerce an attribute (birth_d) unless its type (Maybe[Birth_d]) has a coercion
.完整的测试代码如下:
package Student;
use Moose;
use Moose::Util::TypeConstraints;
use DateTime::Format::MySQL;
class_type 'Birth_d', { class => 'DateTime' };
coerce 'Birth_d',
from 'Str',
via { DateTime::Format::MySQL->parse_date( $_ ) };
has 'name' => (
isa => 'Str',
is => 'ro',
);
has 'birth_d' => (
isa => 'Maybe[Birth_d]', # This works: isa => 'Birth_d'
coerce => 1,
is => 'ro',
);
package main;
use Test::More;
my $student = Student->new(
name => 'Johnnie Appleseed',
birth_d => '2015-01-01'
);
is ( $student->birth_d->ymd(), '2015-01-01' );
my $student2 = Student->new(
name => 'Foo Bar',
birth_d => undef
);
is( $student2->birth_d, undef );
更换
isa => 'Maybe[Birth_d]'
与 isa => 'Birth_d'
工作,但不是需要的。我需要将birth_d 设为可选,如果未提供,则应为undef。我应该补充一点,我尝试使用 MooseX::Types 将这个 Birth_d 类型藏在一个单独的地方,但发现它对裸词的傲慢使用有点不正统,所以我慢慢地后退了。如果这样做有意义,我愿意重新考虑它。
最佳答案
驼鹿 does not do any chaining of coercions ,换句话说,您必须明确告诉它如何转换为 Maybe[Birth_d]
.
您可以通过重用现有的强制转换到 Birth_d
来做到这一点。 :
package Student;
use Moose;
use Moose::Util::TypeConstraints;
use DateTime::Format::MySQL;
# save the Moose::Meta::TypeConstraint object
# you can also get it with find_type_constraint('Birth_d')
my $birth_d = class_type 'Birth_d', { class => 'DateTime' };
coerce 'Birth_d',
from 'Str',
via { DateTime::Format::MySQL->parse_date( $_ ) };
subtype 'MaybeBirth_d',
as 'Maybe[Birth_d]';
coerce 'Maybe[Birth_d]',
from 'Str|Undef',
via { $birth_d->coerce($_) };
has 'name' => (
isa => 'Str',
is => 'ro',
);
has 'birth_d' => (
isa => 'Maybe[Birth_d]',
coerce => 1,
is => 'ro',
predicate => 'has_birth_d', # as per your comment
);
package main;
use Test::More;
my $student = Student->new(
name => 'Johnnie Appleseed',
birth_d => '2015-01-01'
);
is ( $student->birth_d->ymd(), '2015-01-01' );
my $student2 = Student->new(
name => 'Foo Bar',
birth_d => undef
);
is( $student2->birth_d, undef );
ok( $student2->has_birth_d );
done_testing;
关于perl - Attribute is => 'Maybe[SomeSubtype]' 返回 Attribute() 不传递类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44146338/