[tpm] Moo + Type::Tiny

Dave Doyle dave.s.doyle at gmail.com
Mon Aug 18 07:22:51 PDT 2014


Hello TPM,

Just an interesting note to those who saw my Type::Tiny talk a few months
back.

A new version of Moo was just released and I noted that to do a coercion
with Type::Tiny on an attribute you had to do the following:

has lines => (
    is     => 'rw',
    isa    => MyType
    coerce => MyType->coercion,
);

This was a bit restrictive because you HAD to create a named type to get
the coercion because of the need for the second call.  However, Moo's
newest release now supports coerce => 1 where the isa is a blessed object
with a coerce or coercion method which means you can do this:

has lines => (
    is     => 'rw',
    isa    => MyType,
    coerce => 1,
);

This is great, because this means you can now define a type using the base
types (remember, never add a coercion directly to a base type), on the fly
with the plus_coercions and have it work:

use Types::Standard qw{ ArrayRef Split };
has lines => (
    is     => 'rw',
    isa    => ArrayRef->plus_coercions( Split[ qr{\n} ] ),
    coerce => 1,
);

This will require an arrayref, but will coerce a string into an arrayref.
 Now you need not do simple one-time only used types in a library.

D
--
dave.s.doyle at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/toronto-pm/attachments/20140818/f44d450b/attachment.html>


More information about the toronto-pm mailing list