Is there a way to use Moose :: Exporter from a Moose object?

I am looking for a way to configure some helper methods from a Moose parent class , rather than a standalone class utility. If possible, it would be a more transparent way to add Moose sugar to the modules, since this does not require explicitly requiring any auxiliary modules (since everything will happen through the announcement extends).

Based on the example provided in the documentation , this is roughly what I am going to do:

package Parent;

use Moose;

Moose::Exporter->setup_import_methods(
    with_meta => [ 'has_rw' ],
    as_is     => [ 'thing' ],
    also      => 'Moose',
);

sub has_rw {
    my ( $meta, $name, %options ) = @_;
    $meta->add_attribute(
        $name,
        is => 'rw',
        %options,
    );
}

# then later ...
package Child;

use Moose;
extends 'Parent';

has 'name';
has_rw 'size';
thing;

However, this does not work:

perl -I. -MChild -wle'$obj = Child->new(size => 1); print $obj->size'
String found where operator expected at Child.pm line 10, near "has_rw 'size'"
        (Do you need to predeclare has_rw?)
syntax error at Child.pm line 10, near "has_rw 'size'"
Bareword "thing" not allowed while "strict subs" in use at Child.pm line 12.
Compilation failed in require.
BEGIN failed--compilation aborted.

PS. (with Role;, extends Parent;), .

+3
1

, . - , , - . , "" Moose + A Custom Sugar, , Moose, :

package MySugar;
use strict;
use Moose::Exporter;

Moose::Exporter->setup_import_methods(
    with_meta => [ 'has_rw' ],
    as_is     => [ 'thing' ],
    also      => 'Moose',
);

sub has_rw {
    my ( $meta, $name, %options ) = @_;
    $meta->add_attribute(
        $name,
        is => 'rw',
        %options,
    );
}

:

package MyApp;
use MySugar; # imports everything from Moose + has_rw and thing    
extends(Parent);

has_rw 'name';
has 'size';
thing;

MooseX::POE, . , extends , , , .

UPDATE: Parent , Moose:: Object.

package Parent::Methods;
use 5.10.0;
use Moose::Role;

sub something_special { say 'sparkles' }

Moose:: Exporter MySugar,

Moose::Exporter->setup_import_methods(
    apply_base_class_roles => 'Parent::Methods',
    with_meta              => ['has_rw'],
    as_is                  => ['thing'],
    also                   => 'Moose',
);

package MyApp;
use MySugar; 

has_rw 'name';
has 'size';
thing;

package main;
MyApp->new->something_special; # prints sparkles

, .

+7

Source: https://habr.com/ru/post/1724451/


All Articles