I'd like to implement simple method chaining, for that methods must return objects. Since my code is using Moose already and my future classes are almost empty and return only one attribute with instance of another class I decided to generate them programmatically with Moose::Meta::Class (that is subclass of Class::MOP::Class). First time working with Moose metaclasses so I wrote a simple code to try:
package Cat;
use Moose;
package Generator;
use Moose;
sub generate {
Class::MOP::Class->create(
'Siberian' => (
methods => {
echo => sub { print 'yeah!' }
}
)
);
Class::MOP::Class->create(
'Tiger' => (
attributes => [
Class::MOP::Attribute->new('Siberian' => (
default => sub { require Siberian; Siberian->new; }
)),
],
)
);
Cat->meta->add_attribute(Class::MOP::Attribute->new(
Tiger => (
default => sub { require Tiger; Tiger->new }
)
));
print "Generation done!\n";
}
generate();
package main;
use Generator;
my $a = Cat->new;
warn $a->Tiger->Siberian->echo; # must print 'yeah!' but prints Can't locate object method "new" via package "Tiger" at dynamic.pl line 33
Instead of expected yeah! in output I see
Can't locate object method "new" via package "Tiger" at dynamic.pl
line 33
What is wrong ?
Who will respond to constructor creation?
Another way is using of metaclass variables directly.
https://gist.github.com/akzhan/421579163dfc86f570809f50d239800f
See the following fragment of Perl code which is based on Moose:
$BusinessClass->meta->add_attribute($Key => { is => $rorw,
isa => $MooseType,
lazy => 0,
required => 0,
reader => sub { $_[0]->ORM->{$Key} },
writer => sub { $_[0]->ORM->newVal($Key, $_[1]) },
predicate => "has_$Key",
});
I receive the error:
bad accessor/reader/writer/predicate/clearer format, must be a HASH ref at /usr/local/lib/perl5/site_perl/mach/5.20/Class/MOP/Class.pm line 899
The reason of the error is clear: reader and writer must be string names of functions.
But what to do it in this specific case? I do not want to create a new function for each of a hundred ORM fields (ORM attribute here is a tied hash). So I can't pass a string here, I need a closure.
Thus my coding needs resulted in a contradiction. I don't know what to do.
The above was a fragment of real code. Now I present a minimal example:
#!/usr/bin/perl
my #Fields = qw( af sdaf gdsg ewwq fsf ); # pretend that we have 100 fields
# Imagine that this is a tied hash with 100 fields
my %Data = map { $_ => rand } #Fields;
package Test;
use Moose;
foreach my $Key (#Fields) {
__PACKAGE__->meta->add_attribute($Key => { is => 'rw',
isa => 'Str',
lazy => 0,
required => 0,
reader => sub { $Data{$Key} },
writer => sub { $Data{$Key} = $_[1] },
});
}
Running it results in:
$ ./test.pl
bad accessor/reader/writer/predicate/clearer format, must be a HASH ref at /usr/lib/i386-linux-gnu/perl5/5.22/Class/MOP/Class.pm line 899
Class::MOP::Class::try {...} at /usr/share/perl5/Try/Tiny.pm line 92
eval {...} at /usr/share/perl5/Try/Tiny.pm line 83
Try::Tiny::try('CODE(0x9dc6cec)', 'Try::Tiny::Catch=REF(0x9ea0c60)') called at /usr/lib/i386-linux-gnu/perl5/5.22/Class/MOP/Class.pm line 904
Class::MOP::Class::_post_add_attribute('Moose::Meta::Class=HASH(0x9dc13f4)', 'Moose::Meta::Attribute=HASH(0x9dc6b5c)') called at /usr/lib/i386-linux-gnu/perl5/5.22/Class/MOP/Mixin/HasAttributes.pm line 39
Class::MOP::Mixin::HasAttributes::add_attribute('Moose::Meta::Class=HASH(0x9dc13f4)', 'Moose::Meta::Attribute=HASH(0x9dc6b5c)') called at /usr/lib/i386-linux-gnu/perl5/5.22/Moose/Meta/Class.pm line 572
Moose::Meta::Class::add_attribute('Moose::Meta::Class=HASH(0x9dc13f4)', 'af', 'HASH(0x9ea13a4)') called at test.pl line 18
I don't know what to do (how to create "dynamic" (closure-like) accessors, without writing an individual function for each of the 100 fields?)
I think changing the reader and writer methods like that requires an unhealthy level of insanity. If you want to, take a look at the source code of Class::MOP::Method::Accessor, which is used under the hood to create the accessors.
Instead, I suggest to just overwrite (or attach) the functionality to the Moose-generated readers using an around method modifier. To get that to work with sub-classes, you can use Class::Method::Modifiers instead of the Moose around.
package Foo::Subclass;
use Moose;
extends 'Foo';
package Foo;
use Moose;
package main;
require Class::Method::Modifiers; # no import because it would overwrite Moose
my #Fields = qw( af sdaf gdsg ewwq fsf ); # pretend that we have 100 fields
# Imagine that this is a tied hash with 100 fields
my %Data = map { $_ => rand } #Fields;
my $class = 'Foo::Subclass';
foreach my $Key (#Fields) {
$class->meta->add_attribute(
$Key => {
is => 'rw',
isa => 'Str',
lazy => 0,
required => 0,
}
);
Class::Method::Modifiers::around( "${class}::$Key", sub {
my $orig = shift;
my $self = shift;
$self->$orig(#_); # just so Moose is up to speed
# writer
$Data{$Key} = $_[0] if #_;
return $Data{$Key};
});
}
And then run a test.
package main;
use Data::Printer;
use v5.10;
my $foo = Test->new;
say $foo->sdaf;
$foo->sdaf('foobar');
say $foo->sdaf;
p %Data;
p $foo;
Here's the STDOUT/STDERR from my machine.
{
af 0.972962507120432,
ewwq 0.959195914302605,
fsf 0.719139421719849,
gdsg 0.140205658312095,
sdaf "foobar"
}
Foo::Subclass {
Parents Foo
Linear #ISA Foo::Subclass, Foo, Moose::Object
public methods (6) : af, ewwq, fsf, gdsg, meta, sdaf
private methods (0)
internals: {
sdaf "foobar"
}
}
0.885114977459551
foobar
As you can see, Moose doesn't really know about the values inside of the hash, but if you use the accessors, it will read and write them. The Moose object will slowly fill up with new values when you use the writer, but otherwise the values inside of the Moose object do not really matter.
It's cool that it's possible to add them in sub classes or mix them in in roles. My problem is that it seems method modifiers from the base class get deactivated when subclasses redefine the method itself (not the modifier). Maybe I'm understanding method modifiers wrong. Example:
use feature 'say';
package Foo;
use Moose;
has called => (is => 'rw', isa => 'Bool', default => 0);
sub call { 'Foo called' }
after call => sub { shift->called(1) };
my $foo = Foo->new();
say $foo->called; # 0
say $foo->call; # Foo called
say $foo->called; # 1
package Bar;
use Moose;
extends 'Foo';
sub call { 'Bar called' }
my $bar = Bar->new();
say $bar->called; # 0
say $bar->call; # Bar called
say $bar->called; # 0
I expected the last output to be 1 like with $foo. What am I doing wrong?
What happens is this
you define a Foo::call
you modify that with after
you define a Bar::call that doesn't call Foo::Call
The modifiers are not magical runtime things, but class-definition time things. To do what you try to do here you'd have to structure your code differently
#RobEarl posted a link to a very similar question. The solution posted over there was to use augment and although it looks a bit strange and its use is controversial, it could solve my problem:
package Foo;
use Moose;
has called => (is => 'rw', isa => 'Bool', default => 0);
sub call { inner(); shift->called(1); 'Foo called' }
package Bar;
use Moose;
extends 'Foo';
augment call => sub { 'Bar called' };
my $bar = Bar->new();
say $bar->called; # 0
say $bar->call; # Bar called
say $bar->called; # 1
I've found that if a subclass adds a trigger, then method modifiers from the base class don't run. This seems like a Moose bug, or at least non-intuitive. Here's my example:
package Foo {
use Moose;
has 'foo' => (
is => 'rw',
isa => 'Str',
);
before 'foo' => sub {
warn "before foo";
};
};
package FooChild {
use Moose;
extends 'Foo';
has '+foo' => ( trigger => \&my_trigger, );
sub my_trigger {
warn 'this is my_trigger';
}
};
my $fc = FooChild->new();
$fc->foo(10);
If you run this example, only the "this is my_trigger" warn runs, and the "before" modifier is ignored. I'm using Perl 5.14.2 with Moose 2.0402.
Is this correct behavior? It doesn't seem right, especially since the trigger will fire after the before when the trigger is defined directly in the base class.
On the principle that you should not be able to distinguish between inherited code and code in the class, I'd call this a bug.
It appears to be a general problem where adding to an attribute removes method modifiers. This code demonstrates your bug without involving triggers.
package Foo {
use Moose;
has 'foo' => (
is => 'rw',
isa => 'Str',
default => 5,
);
before 'foo' => sub {
warn "before foo";
};
};
package FooChild {
use Moose;
extends 'Foo';
has '+foo' => ( default => 99 );
};
my $fc = FooChild->new();
print $fc->foo;
Please report this to the Moose folks.
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 ...
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? :)
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
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.