3

Having trouble figuring out the syntax (which I'm sure is obvious and I'm stupid) for pushing to a Moose array. This is a continuation of this question. it seems to me that I need to more than a simple value for my specific case. Trying to implement it using a Moose-ish way (maybe that's wrong?) but I'm obviously not doing it right.

use Moose::Role;
has 'tid_stack' => (
    traits => ['Array'],
    is     => 'rw',
    isa    => 'ArrayRef[Str]',
    default => sub { [] },
);


around 'process' => sub {
    my $orig = shift;
    my $self = shift;
    my ( $template ) = @_;

    $self->tid_stack->push( get_hrtid( $template ) );

    $self->$orig(@_)
};
Community
  • 1
  • 1
xenoterracide
  • 16,274
  • 24
  • 118
  • 243

1 Answers1

9

You've misunderstood what traits => ['Array'] does. That allows you to set up handles methods. It does not allow you to call methods like push directly. You need to use Moose::Autobox for that (and you don't need the Array trait).

Or you could do:

has 'tid_stack' => (
    traits => ['Array'],
    is     => 'rw',
    isa    => 'ArrayRef[Str]',
    default => sub { [] },
    handles => {
      push_tid => 'push',
    },
);

...

    $self->push_tid( get_hrtid( $template ) );
cjm
  • 61,471
  • 9
  • 126
  • 175
  • ugh... tried this.... it's driving me nuts... I know that get_hrtid returns the proper thing... but when I try to push it like this it's still not working, moose later complains of trying to operate on empty arrays. – xenoterracide Aug 15 '10 at 15:32
  • @xenoterracide: I can't see anything wrong with the above code, can you give a more detailed error description? What code are you currently trying, and what is the error you get? – phaylon Aug 15 '10 at 16:10
  • with the help of debolaz I have seemingly figured out what was wrong with what I was trying... apparently I needed to make it `lazy` (on top of this) though why that fixed my problem I haven't yet determined. – xenoterracide Aug 15 '10 at 16:59
  • @xenoterracide, maybe your `around` method was getting called during object initialization and `tid_stack` wasn't initialized yet? Making it lazy causes it to get initialized on demand. – cjm Aug 15 '10 at 17:37