Search code examples
perlmoose

How to use Moose to add convenience functions for array attributes?


This is a basic question, I fear. Take a look at the following code. I'd like to know whether there is a way to declare the slices attribute in such a way as to avoid the boilerplate of get_slices and add_slice.

package Gurke;
use Moose;

has slices => is => 'rw', isa => 'ArrayRef[Str]', default => sub { [] };

sub get_slices { return @{ $_[0]->slices } }

sub add_slice {
    my( $self, $slice ) = @_;
    push @{ $self->slices }, $slice;
    return;
}

no Moose;
__PACKAGE__->meta->make_immutable;

package main; # now a small test for the above package
use strict;
use warnings;
use Test::More;
my $gu = Gurke->new;
$gu->add_slice( 'eins' );
$gu->add_slice( 'zwei' );
$gu->add_slice( 'drei' );
my @sl = $gu->get_slices;
is shift @sl, 'eins';
is shift @sl, 'zwei';
is shift @sl, 'drei';
done_testing;

Thanks!


Solution

  • I'm a Moose beginner, but I think you need this:

    has slices =>
        is => 'rw',
        isa => 'ArrayRef[Str]',
        default => sub { [] },
        traits  => ['Array'],
        handles => {
            add_slice  => 'push',
            get_slices => 'elements',
        },
    ;