I have a few Moose classes with attributes along the lines of

has 'items' => (
    is => 'rw',
    isa => 'ArrayRef[<Foo>]'
);

Generally I tend to add a coercion for the HashRef type into whatever
<Foo> is for each of these attributes, so they will accept either
<Foo>s or hashrefs.

This is all fine when setting the contents of these attributes in
their entirety using ->new( items => [ ... ] ) or ->items( [ ... ] ),
but when it comes to adding items I'm finding myself repeatedly doing
something along the following lines:

sub add_item {
    my( $self, $item ) = @_;
    my $items = $self->items;
    push @$items, $item;
    $self->items( $items );
}

This seems a bit clunky and I'm wondering if there is a better way.

MooseX::AttributeHelpers seems to allow me to auto-generate this type
of method, but I can't work out how to get it to perform coercion on
$item.

I've read through the docs and googled but have not been able to find
a best practice. Is there one and if so, what is it?

Thanks, Will

Reply via email to