运行 Type::Tiny 自定义约束内的强制转换?
Run coercions inside a Type::Tiny custom constraint?
我有一个自定义 DateTime 类型,它定义了从字符串到 DateTime 的强制转换,如下所示:
package Library;
use Type::Library -base, -declare => qw(DateTime);
use DateTime::Format::ISO8601;
class_type DateTime, { class => 'DateTime' };
coerce DateTime, from Str, via { DateTime::Format::ISO8601->parse_datetime($_) };
我想在 Dict 中使用 DateTime 类型,如下所示:
package MyObj;
use Moo;
$constraint = declare MyType, as Dict[ name => Str, date => DateTime ];
has 'whatsis' => ( is => 'ro', isa => $constraint );
然后将其命名为:
use MyObj;
my $obj = MyObj->new( whatsis => { name => 'Something', date => '2016-01-01' } );
我试过将 coerce => 1
添加到 whatsis
的声明中,但没有用。
如何创建继承自 Dict 的自定义类型并运行在成员类型上定义的类型强制转换?
在 https://metacpan.org/pod/distribution/Type-Tiny/lib/Type/Tiny/Manual/Coercions.pod
的大力帮助下
Library.pm:
package Library;
use Type::Library -base, -declare => qw(Datetime);
use Type::Utils -all;
use Types::Standard -all;
use DateTime::Format::ISO8601;
class_type Datetime, { class => 'DateTime' };
coerce Datetime,
from Str, via { DateTime::Format::ISO8601->parse_datetime($_) };
declare 'MyType', as Dict[ name => Str, date => Datetime ], coercion => 1;
MyObj.pm:
package MyObj;
use Moo;
use Library -all;
has 'whatsis' => ( is => 'ro', isa => MyType, coerce => 1 );
tester.pl:
#!perl
use MyObj;
my $obj = MyObj->new( whatsis => { name => 'Something', date => '2016-01-01' } );
use Data::Dumper; print Dumper $obj;
我有一个自定义 DateTime 类型,它定义了从字符串到 DateTime 的强制转换,如下所示:
package Library;
use Type::Library -base, -declare => qw(DateTime);
use DateTime::Format::ISO8601;
class_type DateTime, { class => 'DateTime' };
coerce DateTime, from Str, via { DateTime::Format::ISO8601->parse_datetime($_) };
我想在 Dict 中使用 DateTime 类型,如下所示:
package MyObj;
use Moo;
$constraint = declare MyType, as Dict[ name => Str, date => DateTime ];
has 'whatsis' => ( is => 'ro', isa => $constraint );
然后将其命名为:
use MyObj;
my $obj = MyObj->new( whatsis => { name => 'Something', date => '2016-01-01' } );
我试过将 coerce => 1
添加到 whatsis
的声明中,但没有用。
如何创建继承自 Dict 的自定义类型并运行在成员类型上定义的类型强制转换?
在 https://metacpan.org/pod/distribution/Type-Tiny/lib/Type/Tiny/Manual/Coercions.pod
的大力帮助下Library.pm:
package Library;
use Type::Library -base, -declare => qw(Datetime);
use Type::Utils -all;
use Types::Standard -all;
use DateTime::Format::ISO8601;
class_type Datetime, { class => 'DateTime' };
coerce Datetime,
from Str, via { DateTime::Format::ISO8601->parse_datetime($_) };
declare 'MyType', as Dict[ name => Str, date => Datetime ], coercion => 1;
MyObj.pm:
package MyObj;
use Moo;
use Library -all;
has 'whatsis' => ( is => 'ro', isa => MyType, coerce => 1 );
tester.pl:
#!perl
use MyObj;
my $obj = MyObj->new( whatsis => { name => 'Something', date => '2016-01-01' } );
use Data::Dumper; print Dumper $obj;