Moose - Perl's post-modern Object system

This section contains notes and docs related to Moose. Create additional pages if you feel so inclined.

Resources

Notes and gotchas:

Multiple Role checking in attributes

In Moose attributes, you can check that the provided object does a Role by including does in the attribute

package Foo;
use Moose;
has 'myanimal' => (
    is => 'rw',
    does => 'Flies'
);

But what if you need to know that it can both fly and swim.... you might think that you could do:

package Foo;
use Moose;
has 'myanimal' => (
    is => 'rw',
    does => ['Flies''Swims']  # this does NOT work
);

But you can not. The does constraint does not understand more than one role. Fortunately all is not lost. You can still check both Roles, it just requires a bit more legwork... and the creation of a subtype:

package Foo;
use Moose;
use Moose::Util::TypeConstraints;
# .... 
has 'myanimal' => (
    is => 'rw',
    does => subtype as 'Role' => where { $_->does('Flies') && $_->does('Swims') }
);

Attribute defaults that depend on other attributes

It's good to be lazy with attribute defaults and essay papers. If you have defaults or builders that depend on other values, you need to make them lazy or you will run into a race condition regarding whether the other values have had their defaults set before the other builders run. Best to use lazy => 1 on one or both sets of defaults.

My tags:
 
Popular tags:
 
Powered by Catalyst