Note that there are some explanatory texts on larger screens.

plurals
  1. POApply specific check (beyond Moose types) to Moose attribute
    primarykey
    data
    text
    <p><a href="http://search.cpan.org/dist/Moose/lib/Moose/Manual/Types.pod" rel="nofollow">Moose types</a> are great, but sometimes you need to be more specific. You all know these data type rules: that parameter may only be <code>'A'</code>, <code>'B'</code> or <code>'C'</code>, or only a currency symbol, or must conform to some regular expression.</p> <p>Take a look at the following example which has two constrained attributes, one must be either <code>'m'</code> or <code>'f'</code>, the other must be a valid ISO date. What's the best way in Moose to specify these constraints? I'd think of the SQL <code>CHECK</code> clause, but AFAICS there is no <code>check</code> keyword in Moose. So I used <code>trigger</code>, but it sounds wrong. Anyone has a better answer?</p> <pre><code>package Person; use Moose; has gender =&gt; is =&gt; 'rw', isa =&gt; 'Str', trigger =&gt; sub { confess 'either m or f' if $_[1] !~ m/^m|f$/ }; has name =&gt; is =&gt; 'rw', isa =&gt; 'Str'; has dateOfBirth =&gt; is =&gt; 'rw', isa =&gt; 'Str', trigger =&gt; sub { confess 'not an ISO date' if $_[1] !~ m/^\d\d\d\d-\d\d-\d\d$/ }; no Moose; __PACKAGE__-&gt;meta-&gt;make_immutable; package main; use Test::More; use Test::Exception; dies_ok { Person-&gt;new( gender =&gt; 42 ) } 'gender must be m or f'; dies_ok { Person-&gt;new( dateOfBirth =&gt; 42 ) } 'must be an ISO date'; done_testing; </code></pre> <p>Here's what I wound up using:</p> <pre><code>package Blabla::Customer; use Moose::Util::TypeConstraints; use Moose; subtype ISODate =&gt; as 'Str' =&gt; where { /^\d\d\d\d-\d\d-\d\d$/ }; has id =&gt; is =&gt; 'rw', isa =&gt; 'Str'; has gender =&gt; is =&gt; 'rw', isa =&gt; enum ['m', 'f']; has firstname =&gt; is =&gt; 'rw', isa =&gt; 'Str'; has dateOfBirth =&gt; is =&gt; 'rw', isa =&gt; 'ISODate'; no Moose; __PACKAGE__-&gt;meta-&gt;make_immutable; </code></pre> <p>This is Moose version 1.19, in case it matters. I got the following warning for the <em>wrong</em> <code>subtype as =&gt; 'Str', where =&gt; { ... }</code> syntax I erroneously introduced: <code>Calling subtype() with a simple list of parameters is deprecated</code>. So I had to change it a bit according to the fine manual.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload