tags:

views:

42

answers:

2

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?

+1  A: 
lazy_build => 1,

That also marks them lazy, but that's recommended for attributes with a builder.

cjm
+5  A: 
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.)

Ether
I should have thought of this. Just because `has` looks like a declaration, doesn't mean it isn't executable code.
daotoad