Moose types很棒,但有時您需要更具體。大家都知道這些數據類型規則:該參數可能只有'A'
,'B'
或'C'
,或者只有一個貨幣符號,或者必須符合一些正則表達式。適用於穆斯(Moose)屬性的特定支票(超過穆斯類型)
看看下面有兩個約束屬性的示例,其中一個必須是'm'
或'f'
,另一個必須是有效的ISO日期。穆斯有什麼最好的方式來指定這些約束條件?我會想到SQL CHECK
子句,但AFAICS在Moose中沒有check
關鍵字。所以我用trigger
,但聽起來不對。任何人有更好的答案?
package Person;
use Moose;
has gender => is => 'rw', isa => 'Str', trigger =>
sub { confess 'either m or f' if $_[1] !~ m/^m|f$/ };
has name => is => 'rw', isa => 'Str';
has dateOfBirth => is => 'rw', isa => 'Str', trigger =>
sub { confess 'not an ISO date' if $_[1] !~ m/^\d\d\d\d-\d\d-\d\d$/ };
no Moose;
__PACKAGE__->meta->make_immutable;
package main;
use Test::More;
use Test::Exception;
dies_ok { Person->new(gender => 42) } 'gender must be m or f';
dies_ok { Person->new(dateOfBirth => 42) } 'must be an ISO date';
done_testing;
這裏是我結束了使用:
package Blabla::Customer;
use Moose::Util::TypeConstraints;
use Moose;
subtype ISODate => as 'Str' => where { /^\d\d\d\d-\d\d-\d\d$/ };
has id => is => 'rw', isa => 'Str';
has gender => is => 'rw', isa => enum ['m', 'f'];
has firstname => is => 'rw', isa => 'Str';
has dateOfBirth => is => 'rw', isa => 'ISODate';
no Moose;
__PACKAGE__->meta->make_immutable;
這是駝鹿版本1.19,如果它很重要。我得到了以下警告:錯誤subtype as => 'Str', where => { ... }
語法我錯誤地介紹了:Calling subtype() with a simple list of parameters is deprecated
。所以我必須根據精細的手冊稍微改變它。
**答案:**使用自己的類型。 – 2011-04-28 17:39:22