perlmoo

Moo handles => 'Role' not working


For the life of me I can't figure out why this is not working the way the documentation says it should. I have Googled the problem SO searched, looked at the source, etc. Is this a bug or am I doing something wrong that I just can't see.

Here is the code: #!/usr/bin/env perl

use strict;
use warnings;

package Model;

use Moo::Role;

has ObjectID => (
    is => 'rw'
);

package Object;

use Moo; 
use namespace::clean;

has model => (
    is => 'rw',
    handles => 'Model'
);

package main;

my $xo = Object->new;
$xo->ObjectID(12345);

exit;

attempt to run

perl -MCarp::Always t/moohandles.t

and get this

Attempted to access 'model' but it is not set at (eval 26) line 20.
    Object::_assert_model('Object=HASH(0x1dfd118)') called at (eval 25) line 17
    Object::ObjectID('Object=HASH(0x1dfd118)', 12345) called at t/moohandles.t line 27

Solution

  • Delegation essentially expands the $xo->ObjectID method call to $xo->model->ObjectID. But $xo->model is currently unset. You probably want to default it to an object that consumes the Model role.

    Something like this:

    use strict;
    use warnings;
    
    {
      package Model;
      use Moo::Role;
      has ObjectID => (
        is => 'rw',
      );
    }
    
    {
      package ModelClass;
      use Moo;
      with 'Model';
    }
    
    {
      package Object;
      use Moo;
      has model => (
        is => 'rw',
        handles => 'Model',
        builder => sub { ModelClass->new },
      );
    }
    
    my $xo = Object->new;
    $xo->ObjectID(12345);
    print $xo->ObjectID, "\n";