Search code examples
perlmoose

In Moose, how do you declare predicate and clearer methods when defining multiple attributes?


In Moose you can declare a group of attributes at once, assuming the initialization parameters are the same:

has [qw( foo bar baz )] => (
    is => 'ro',
    isa => 'Str',
    required => 1,
);

This is a lovely feature that saves a ton of typing. However, I find myself puzzled about how define a predicate, clearer or even a builder method using this syntax.

has 'foo' => (
    is        => 'ro',
    isa       => 'Str',
    required  => 1,
    clearer   => 'clear_foo',
    predicate => 'has_foo',
);

Is there a parameter I can use that will build standard 'has_X, 'clear_X and _build_X methods for all the attributes in my list?


Solution

  • has $_ => (
        is => 'ro',
        isa => 'Str',
        required => 1,
        clearer => '_clear_' . $_,
        # etc...
    ) for (qw(foo bar baz);
    

    Note that lazy_build => 1 will automatically generate clearers, and predicates, but they will always be public, which is starting to be frowned upon in the Moose community. (I don't think anyone's blogged about this yet, but it's been a topic of conversation on IRC #moose of late.)