Use a single module and get Moose plus several MooseX extensions
Asked Answered
H

3

5

Let's say I have a codebase with a bunch of Moose-based classes and I want them all to use a common set of MooseX::* extension modules. But I don't want each Moose-based class to have to start like this:

package My::Class;

use Moose;
use MooseX::Aliases;
use MooseX::HasDefaults::RO;
use MooseX::StrictConstructor;
...

Instead, I want each class to begin like this:

package MyClass;

use My::Moose;

and have it be exactly equivalent to the above.

My first attempt at implementing this was based on the approach used by Mason::Moose (source):

package My::Moose;

use Moose;
use Moose::Exporter;
use MooseX::Aliases();
use MooseX::StrictConstructor();
use MooseX::HasDefaults::RO();
use Moose::Util::MetaRole;

Moose::Exporter->setup_import_methods(also => [ 'Moose' ]);

sub init_meta {
    my $class = shift;
    my %params = @_;

    my $for_class = $params{for_class};

    Moose->init_meta(@_);
    MooseX::Aliases->init_meta(@_);
    MooseX::StrictConstructor->init_meta(@_);
    MooseX::HasDefaults::RO->init_meta(@_);

    return $for_class->meta();
}

But this approach is not recommended by the folks in the #moose IRC channel on irc.perl.org, and it doesn't always work, depending on the mix of MooseX::* modules. For example, trying to use the My::Moose class above to make My::Class like this:

package My::Class;

use My::Moose;

has foo => (isa => 'Str');

Results in the following error when the class is loaded:

Attribute (foo) of class My::Class has no associated methods (did you mean to provide an "is" argument?)
 at /usr/local/lib/perl5/site_perl/5.12.1/darwin-2level/Moose/Meta/Attribute.pm line 1020.
    Moose::Meta::Attribute::_check_associated_methods('Moose::Meta::Class::__ANON__::SERIAL::2=HASH(0x100bd6f00)') called at /usr/local/lib/perl5/site_perl/5.12.1/darwin-2level/Moose/Meta/Class.pm line 573
    Moose::Meta::Class::add_attribute('Moose::Meta::Class::__ANON__::SERIAL::1=HASH(0x100be2f10)', 'foo', 'isa', 'Str', 'definition_context', 'HASH(0x100bd2eb8)') called at /usr/local/lib/perl5/site_perl/5.12.1/darwin-2level/Moose.pm line 79
    Moose::has('Moose::Meta::Class::__ANON__::SERIAL::1=HASH(0x100be2f10)', 'foo', 'isa', 'Str') called at /usr/local/lib/perl5/site_perl/5.12.1/darwin-2level/Moose/Exporter.pm line 370
    Moose::has('foo', 'isa', 'Str') called at lib/My/Class.pm line 5
    require My/Class.pm called at t.pl line 1
    main::BEGIN() called at lib/My/Class.pm line 0
    eval {...} called at lib/My/Class.pm line 0

The MooseX::HasDefaults::RO should be preventing this error, but it's apparently not being called upon to do its job. Commenting out the MooseX::Aliases->init_meta(@_); line "fixes" the problem, but a) that's one of the modules I want to use, and b) that just further emphasizes the wrongness of this solution. (In particular, init_meta() should only be called once.)

So, I'm open to suggestions, totally ignoring my failed attempt to implement this. Any strategy is welcome as long as if gives the results described at the start of this question.


Based on @Ether's answer, I now have the following (which also doesn't work):

package My::Moose;

use Moose();
use Moose::Exporter;
use MooseX::Aliases();
use MooseX::StrictConstructor();
use MooseX::HasDefaults::RO();

my %class_metaroles = (
    class => [
        'MooseX::StrictConstructor::Trait::Class',
    ],

    attribute => [
        'MooseX::Aliases::Meta::Trait::Attribute', 
        'MooseX::HasDefaults::Meta::IsRO',
     ],
);

my %role_metaroles = (
    role =>
        [ 'MooseX::Aliases::Meta::Trait::Role' ],
    application_to_class =>
        [ 'MooseX::Aliases::Meta::Trait::Role::ApplicationToClass' ],
    application_to_role =>
        [ 'MooseX::Aliases::Meta::Trait::Role::ApplicationToRole' ],
);

if (Moose->VERSION >= 1.9900) {
    push(@{$class_metaroles{class}},
        'MooseX::Aliases::Meta::Trait::Class');

    push(@{$role_metaroles{applied_attribute}}, 
        'MooseX::Aliases::Meta::Trait::Attribute',
        'MooseX::HasDefaults::Meta::IsRO');
}
else {
    push(@{$class_metaroles{constructor}},
        'MooseX::StrictConstructor::Trait::Method::Constructor',
        'MooseX::Aliases::Meta::Trait::Constructor');
}

*alias = \&MooseX::Aliases::alias;

Moose::Exporter->setup_import_methods(
    also => [ 'Moose' ],
    with_meta => ['alias'],
    class_metaroles => \%class_metaroles,
    role_metaroles => \%role_metaroles,
);

With a sample class like this:

package My::Class;

use My::Moose;

has foo => (isa => 'Str');

I get this error:

Attribute (foo) of class My::Class has no associated methods (did you mean to provide an "is" argument?) at ...

With a sample class like this:

package My::Class;

use My::Moose;

has foo => (isa => 'Str', alias => 'bar');

I get this error:

Found unknown argument(s) passed to 'foo' attribute constructor in 'Moose::Meta::Attribute': alias at ...
Hawger answered 18/4, 2012 at 19:10 Comment(1)
"has no associated methods" is an expected warning when you declare an attribute with no methods (which is what you get when you leave off "is", and also provide no delegations)...Enenstein
E
3

As discussed, you shouldn't be calling other extensions' init_meta methods directly. Instead, you should essentially inline those extensions' init_meta methods: combine what all those methods do, into your own init_meta. This is fragile because now you are tying your module to other modules' innards, which are subject to change at any time.

e.g. to combine MooseX::HasDefaults::IsRO, MooseX::StrictConstructor and MooseX::Aliases, you'd do something like this (warning: untested) (now tested!):

package Mooseish;

use Moose ();
use Moose::Exporter;
use MooseX::StrictConstructor ();
use MooseX::Aliases ();

my %class_metaroles = (
    class => ['MooseX::StrictConstructor::Trait::Class'],
    attribute => [
        'MooseX::Aliases::Meta::Trait::Attribute',
        'MooseX::HasDefaults::Meta::IsRO',
    ],
);
my %role_metaroles = (
    role =>
        ['MooseX::Aliases::Meta::Trait::Role'],
    application_to_class =>
        ['MooseX::Aliases::Meta::Trait::Role::ApplicationToClass'],
    application_to_role =>
        ['MooseX::Aliases::Meta::Trait::Role::ApplicationToRole'],
);

if (Moose->VERSION >= 1.9900) {
    push @{$class_metaroles{class}}, 'MooseX::Aliases::Meta::Trait::Class';
    push @{$role_metaroles{applied_attribute}}, 'MooseX::Aliases::Meta::Trait::Attribute';
}
else {
    push @{$class_metaroles{constructor}},
        'MooseX::StrictConstructor::Trait::Method::Constructor',
        'MooseX::Aliases::Meta::Trait::Constructor';
}

*alias = \&MooseX::Aliases::alias;

Moose::Exporter->setup_import_methods(
    also => ['Moose'],
    with_meta => ['alias'],
    class_metaroles => \%class_metaroles,
    role_metaroles => \%role_metaroles,
);

1;

This can be tested with this class and tests:

package MyObject;
use Mooseish;

sub foo { 1 }

has this => (
    isa => 'Str',
    alias => 'that',
);

1;

use strict;
use warnings;
use MyObject;
use Test::More;
use Test::Fatal;

like(
    exception { MyObject->new(does_not_exist => 1) },
    qr/unknown attribute.*does_not_exist/,
    'strict constructor behaviour is present',
);

can_ok('MyObject', qw(alias this that has with foo));

my $obj = MyObject->new(this => 'thing');
is($obj->that, 'thing', 'can access attribute by its aliased name');

like(
    exception { $obj->this('new value') },
    qr/Cannot assign a value to a read-only accessor/,
    'attribute defaults to read-only',
);

done_testing;

Which prints:

ok 1 - strict constructor behaviour is present
ok 2 - MyObject->can(...)
ok 3 - can access attribute by its aliased name
ok 4 - attribute defaults to read-only
1..4
Enenstein answered 18/4, 2012 at 19:54 Comment(10)
Yikes, that is quite an undertaking, and as you noted, is not exactly in keeping with the idea of encapsulated extension modules. But I'll give it a try…Hawger
I think the setup_import_methods() call is wrong, because "has" isn't being exported now (among others, presumably).Hawger
@John: for the Moose-specific bits, just add also => ['Moose'] to the setup_import_methods call - I think there is a recipe in the docs for this.Enenstein
Yeah, I added that, but it still isn't working. I'll put what I have so far in the question.Hawger
@John: that's odd; the only thing I see different from what the docs for Moose::Exporter say is you are making your exporter class moosey itself - change use Moose; to use Moose ();Enenstein
I changed use Moose; to use Moose(); in My/Moose.pm. No change in behavior.Hawger
@John: I'm not sure where you are running into difficulty, but I've updated my answer with code that works, including tests.Enenstein
I copied and pasted your code into the appropriate files (Mooseish.pm, MyObject.pm, and test.pl) and ran test.pl and got this error: Found unknown argument(s) passed to 'this' attribute constructor in 'Moose::Meta::Attribute': alias at /usr/local/lib/perl5/site_perl/5.14.2/darwin-2level/Moose/Meta/Attribute.pm line 101 ... (Using perl 5.14.2, latest stable CPAN versions of everything.)Hawger
@John: sorry, cannot repro; I'm running latest versions of the MooseX modules, and Moose-2.0502. The code that I pasted here runs without errors.Enenstein
@John: awesome! I suspect it was the bug fix in 2.5000, relating to the order that init_meta methods are called, that made the difference.Enenstein
T
7

I might get raked over the coals for this, but when in doubt, lie :)

package MyMoose;                                                                                                                                                               

use strict;
use warnings;
use Carp 'confess';

sub import {
    my $caller = caller;
    eval <<"END" or confess("Loading MyMoose failed: $@");
    package $caller;
    use Moose;
    use MooseX::StrictConstructor;
    use MooseX::FollowPBP;
    1;
END
}

1;

By doing that, you're evaling the use statements into the calling package. In other words, you're lying to them about what class they are used in.

And here you declare your person:

package MyPerson;                                                                                                                                                              
use MyMoose;

has first_name => ( is => 'ro', required => 1 );
has last_name  => ( is => 'rw', required => 1 );

1;

And tests!

use lib 'lib';                                                                                                                                                                 
use MyPerson;
use Test::Most;

throws_ok { MyPerson->new( first_name => 'Bob' ) }
qr/\QAttribute (last_name) is required/,
  'Required attributes should be required';

throws_ok {
    MyPerson->new(
        first_name => 'Billy',
        last_name  => 'Bob',
        what       => '?',
    );
}
qr/\Qunknown attribute(s) init_arg passed to the constructor: what/,
  '... and unknown keys should throw an error';

my $person;
lives_ok { $person = MyPerson->new( first_name => 'Billy', last_name => 'Bob' ) }
'Calling the constructor with valid arguments should succeed';

isa_ok $person, 'MyPerson';
can_ok $person, qw/get_first_name get_last_name set_last_name/;
ok !$person->can("set_first_name"),
  '... but we should not be able to set the first name';
done_testing;

And the test results:

ok 1 - Required attributes should be required
ok 2 - ... and unknown keys should throw an error
ok 3 - Calling the constructor with valid arguments should succeed
ok 4 - The object isa MyPerson
ok 5 - MyPerson->can(...)
ok 6 - ... but we should not be able to set the first name
1..6

Let's keep this our little secret, shall we? :)

Telephoto answered 23/4, 2012 at 18:39 Comment(5)
lbr comments: ![](cdn.memegenerator.net/instances/400x/19290874.jpg)Barrada
daxim: I'll take "Insanely brilliant" for $500, please :)Telephoto
That's…pretty terrible :) In addition to being ugly, incurring a string eval on every module load can't be good for performance. Nevertheless, it does work. I just hope there's a better solution. (And if there isn't, I hope the Moose folks come up with one!)Hawger
This happens to be what Any::Moose does ( github.com/sartak/any-moose/blob/master/lib/Any/… ) and I haven't had any feedback that it's slow or broken. "Ugly" I'll welcome though.Beanie
@JohnSiracusa Depending upon what you mean by "performance", I'm not sure it's bad. Of course, my code tends to run in persistent environments and I'm less worried about the start up costs (and my test suites generally run in a single process, so I don't worry about start up costs there, either). That being said, I suspect you'll find this an easier and less fragile solution than "correct" ones :)Telephoto
E
3

As discussed, you shouldn't be calling other extensions' init_meta methods directly. Instead, you should essentially inline those extensions' init_meta methods: combine what all those methods do, into your own init_meta. This is fragile because now you are tying your module to other modules' innards, which are subject to change at any time.

e.g. to combine MooseX::HasDefaults::IsRO, MooseX::StrictConstructor and MooseX::Aliases, you'd do something like this (warning: untested) (now tested!):

package Mooseish;

use Moose ();
use Moose::Exporter;
use MooseX::StrictConstructor ();
use MooseX::Aliases ();

my %class_metaroles = (
    class => ['MooseX::StrictConstructor::Trait::Class'],
    attribute => [
        'MooseX::Aliases::Meta::Trait::Attribute',
        'MooseX::HasDefaults::Meta::IsRO',
    ],
);
my %role_metaroles = (
    role =>
        ['MooseX::Aliases::Meta::Trait::Role'],
    application_to_class =>
        ['MooseX::Aliases::Meta::Trait::Role::ApplicationToClass'],
    application_to_role =>
        ['MooseX::Aliases::Meta::Trait::Role::ApplicationToRole'],
);

if (Moose->VERSION >= 1.9900) {
    push @{$class_metaroles{class}}, 'MooseX::Aliases::Meta::Trait::Class';
    push @{$role_metaroles{applied_attribute}}, 'MooseX::Aliases::Meta::Trait::Attribute';
}
else {
    push @{$class_metaroles{constructor}},
        'MooseX::StrictConstructor::Trait::Method::Constructor',
        'MooseX::Aliases::Meta::Trait::Constructor';
}

*alias = \&MooseX::Aliases::alias;

Moose::Exporter->setup_import_methods(
    also => ['Moose'],
    with_meta => ['alias'],
    class_metaroles => \%class_metaroles,
    role_metaroles => \%role_metaroles,
);

1;

This can be tested with this class and tests:

package MyObject;
use Mooseish;

sub foo { 1 }

has this => (
    isa => 'Str',
    alias => 'that',
);

1;

use strict;
use warnings;
use MyObject;
use Test::More;
use Test::Fatal;

like(
    exception { MyObject->new(does_not_exist => 1) },
    qr/unknown attribute.*does_not_exist/,
    'strict constructor behaviour is present',
);

can_ok('MyObject', qw(alias this that has with foo));

my $obj = MyObject->new(this => 'thing');
is($obj->that, 'thing', 'can access attribute by its aliased name');

like(
    exception { $obj->this('new value') },
    qr/Cannot assign a value to a read-only accessor/,
    'attribute defaults to read-only',
);

done_testing;

Which prints:

ok 1 - strict constructor behaviour is present
ok 2 - MyObject->can(...)
ok 3 - can access attribute by its aliased name
ok 4 - attribute defaults to read-only
1..4
Enenstein answered 18/4, 2012 at 19:54 Comment(10)
Yikes, that is quite an undertaking, and as you noted, is not exactly in keeping with the idea of encapsulated extension modules. But I'll give it a try…Hawger
I think the setup_import_methods() call is wrong, because "has" isn't being exported now (among others, presumably).Hawger
@John: for the Moose-specific bits, just add also => ['Moose'] to the setup_import_methods call - I think there is a recipe in the docs for this.Enenstein
Yeah, I added that, but it still isn't working. I'll put what I have so far in the question.Hawger
@John: that's odd; the only thing I see different from what the docs for Moose::Exporter say is you are making your exporter class moosey itself - change use Moose; to use Moose ();Enenstein
I changed use Moose; to use Moose(); in My/Moose.pm. No change in behavior.Hawger
@John: I'm not sure where you are running into difficulty, but I've updated my answer with code that works, including tests.Enenstein
I copied and pasted your code into the appropriate files (Mooseish.pm, MyObject.pm, and test.pl) and ran test.pl and got this error: Found unknown argument(s) passed to 'this' attribute constructor in 'Moose::Meta::Attribute': alias at /usr/local/lib/perl5/site_perl/5.14.2/darwin-2level/Moose/Meta/Attribute.pm line 101 ... (Using perl 5.14.2, latest stable CPAN versions of everything.)Hawger
@John: sorry, cannot repro; I'm running latest versions of the MooseX modules, and Moose-2.0502. The code that I pasted here runs without errors.Enenstein
@John: awesome! I suspect it was the bug fix in 2.5000, relating to the order that init_meta methods are called, that made the difference.Enenstein
V
1

So long as the MooseX you want to use are all well-behaved and use Moose::Exporter, you can use Moose::Exporter to create a package that will behave like Moose for you:

package MyMoose;

use strict;
use warnings;

use Moose::Exporter;
use MooseX::One ();
use MooseX::Two ();

Moose::Exporter->setup_import_methods(
    also => [ qw{ Moose MooseX::One MooseX::Two } ],
);

1;

Note that in also we're using the name of the package that the Moose extension using Moose::Exporter (generally the main package from the extension), and NOT using any of the trait application bits. Moose::Exporter handles that all behind the scenes.

The advantage here? Everything works as expected, all sugar from Moose and extensions is installed and can be removed via 'no MyMoose;'.

I should point out here that some extensions do not play well with others, usually due to their not anticipating that they'll be required to coexist in harmony with others. Luckily, these are becoming increasingly uncommon.

For a larger scale example, check out Reindeer on the CPAN, which collects several extensions and integrates them together in a coherent, consistent fashion.

Voncile answered 25/4, 2012 at 0:31 Comment(2)
Apparently the "badly behaved" modules are not quite rare enough. When I try it with the modules in the question, I get this error: Circular reference in 'also' parameter to Moose::Exporter between MooseX::HasDefaults::ROHawger
Hmmm... yeah. Looks like it's been around a while, too: rt.cpan.org/Public/Bug/Display.html?id=63818 I suspect this might be the time to file a bug against HasDefaults::RO, asking that Moose be removed from the 'also' list.Voncile

© 2022 - 2024 — McMap. All rights reserved.