Search code examples
perldelegatesmoose

How can I delegate to a sub object of an object with Moose handles?


The Moose documentation says that I can delegate to the object thing easily enough.

has 'thing' => (
   ...
   handles => { set_foo => [ set => 'foo' ] },
);

# $self->set_foo(...) calls $self->thing->set('foo', ...)

But I really want to delegate to an object on thing, specifically a datetime object

has 'thing' => (
   ...
   handles => {
       get_month => { datetime ... },
   },
);

# $self->get_month calls $self->thing->datetime->month;

how would I have to construct handles to get it to do this?


Solution

  • has thing => (
       ...
       handles => {
          get_month => sub { $_[0]->thing->datetime->month },
       },
    );
    

    Short of adding datetime_month to thing, you'll have to write your own delegator.