加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 如何使用Types :: Path :: Tiny with Moo

发布时间:2020-12-16 06:26:17 所属栏目:大数据 来源:网络整理
导读:我在这个网站上的第一个问题,我来得很快.我是开发人员,我主要使用 Python和Perl.我很有激情,我非常喜欢这个发展. 我的第一个问题是关于Perl,Moo和Type :: Tiny. Type :: Tiny当然是与Moo一起使用的一个很棒的模块,但我会在另一个问题上回到这个主题. 我发现
我在这个网站上的第一个问题,我来得很快.我是开发人员,我主要使用 Python和Perl.我很有激情,我非常喜欢这个发展.

我的第一个问题是关于Perl,Moo和Type :: Tiny. Type :: Tiny当然是与Moo一起使用的一个很棒的模块,但我会在另一个问题上回到这个主题.

我发现了Types :: Path :: Tiny Moose和Moo的模块强制,所以我尝试在我的类中创建一个属性目录,如documentation所述,因为我的项目在Moose工作,但是因为我搬到了Moo,它不再有效:

package MahewinBlogEngine::Common;

use strict;
use warnings;

use feature "state";

use Moo;
use Types::Path::Tiny qw/Path AbsPath/;

use CHI;
use MahewinBlogEngine::Renderer;

use Type::Params qw( compile );
use Types::Standard qw( slurpy Object Str HashRef ArrayRef );


=attr directory

rw,required,Str. The directory contain articles.

=cut

has 'directory' => (
    is       => 'rw',isa      => AbsPath,required => 1,coerce   => 1,);

在我的测试目录中:

my $articles = MahewinBlogEngine->articles( directory => getcwd() . '/t/articles' );

错误是:

Invalid coerce '1' for MahewinBlogEngine::Common->directory not a coderef or code-convertible object at /home/hobbestigrou/perl5/perlbrew/perls/perl-5.19.1/lib/site_perl/5.19.1/Method/Generate/Accessor.pm line 618.
Compilation failed in require at /home/hobbestigrou/perl5/perlbrew/perls/perl-5.19.1/lib/site_perl/5.19.1/Module/Runtime.pm line 317.
Compilation failed in require at /home/hobbestigrou/MahewinBlogEngine/lib/MahewinBlogEngine.pm line 8.
BEGIN failed--compilation aborted at /home/hobbestigrou/MahewinBlogEngine/lib/MahewinBlogEngine.pm line 8.
Compilation failed in require at ./benchmark.pl line 10.
BEGIN failed--compilation aborted at ./benchmark.pl line 10.

这是正常的,因为对于Moo,强制是一个coderef所以我试过:

has 'directory' => (
    is       => 'rw',coerce   => sub { return "Path" }
 );

错误是:

value "Path" did not pass type constraint "Path" (not isa Path::Tiny) (in $self->{"directory"}) at (eval 355) line 99.

如果我没有强迫:

value "/home/hobbestigrou/MahewinBlogEngine/t/articles" did not pass type constraint "Path" (not isa Path::Tiny) (in $self->{"directory"}) at (eval 355) line 89.

对于这个简单的问题,我很抱歉,我一定是傻了,想念一些东西,但我看不出我在文档中遗漏了什么.

谢谢

解决方法

没有理由严格使用;并使用警告;如果你使用Moo;因为它为你做了.

您还必须为强制元素提供Moo代码引用,而不是真值.
你通过Type::Tiny调用$type->强制来获得它的方式.

package MahewinBlogEngine::Common;

# not needed with Moo
# use strict;
# use warnings;

use Moo;
use Types::Path::Tiny qw/AbsPath/;

...

has 'directory' => (
    is       => 'rw',coerce   => AbsPath->coercion,);
for( qw'/home ./ ./Documents Documents' ){
  use feature 'say';
  say $_,"t",MahewinBlogEngine::Common->new( directory => $_ )->directory;
}
/home   /home
./      /home/user
./Documents     /home/user/Documents
Documents       /home/user/Documents

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读