MooseX::Types and coercion error - perl

As continue of this answer wow im fighting with the my own Moose "type library" - so trying to use "MooseX::Types".
Based on the above MooseX::Types docs, and "hoobs" comment to the above answer, I defined my own "types" as next:
package MyTypes;
use 5.016;
use Moose;
use MooseX::Types -declare => [qw( Dir File )];
use MooseX::Types::Moose qw( Str );
use Path::Class::Dir;
use Path::Class::File;
class_type Dir, { class => 'Path::Class::Dir' };
coerce Dir, from Str, via { Path::Class::Dir->new($_) };
class_type File, { class => 'Path::Class::File' };
coerce File, from Str, via { Path::Class::File->new($_) };
1;
and used it in my package
package MyDir;
use Moose;
use warnings;
use MyTypes qw(Dir); #to get the Dir type and its coercion
has 'path' => (
is => 'ro',
isa => Dir, # Dir is defined in the package MyTypes
required => 1,
);
1;
and tried with the next short script
use 5.016;
use warnings;
use MyDir;
my $d = MyDir->new(path => "/tmp");
Error:
Attribute (path) does not pass the type constraint because: Validation failed for 'MyTypes::Dir' with value /tmp (not isa Path::Class::Dir) at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 1279.
Moose::Meta::Attribute::verify_against_type_constraint(Moose::Meta::Attribute=HASH(0x7f9e9b1c2618), "/tmp", "instance", MyDir=HASH(0x7f9e9b826bb8)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 1266
Moose::Meta::Attribute::_coerce_and_verify(Moose::Meta::Attribute=HASH(0x7f9e9b1c2618), "/tmp", MyDir=HASH(0x7f9e9b826bb8)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 536
Moose::Meta::Attribute::initialize_instance_slot(Moose::Meta::Attribute=HASH(0x7f9e9b1c2618), Moose::Meta::Instance=HASH(0x7f9e9b1c3588), MyDir=HASH(0x7f9e9b826bb8), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Class/MOP/Class.pm line 525
Class::MOP::Class::_construct_instance(Moose::Meta::Class=HASH(0x7f9e9b9e6990), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Class/MOP/Class.pm line 498
Class::MOP::Class::new_object(Moose::Meta::Class=HASH(0x7f9e9b9e6990), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Class.pm line 284
Moose::Meta::Class::new_object(Moose::Meta::Class=HASH(0x7f9e9b9e6990), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Object.pm line 28
Moose::Object::new("MyDir", "path", "/tmp") called at t.pl line 5
So, doesn't accept the 'Str' and don't do the coercion.
What is wrong in the above few lines? I'm pretty sure than it is really very small bug, because i followed the MooseX::Types docs (at least i hope) - but unable to find the error.
I'm starting be really hopeless with Moose, please HELP...
Ps: My goal is defining all my own "types" in one place (package) and use it everywhere where i need them with one single "use...".

You need to tell Moose that it's OK to use coercion on that attribute. You do this by adding coerce into the attribute definition:
has 'path' => (
is => 'ro',
isa => Dir, # Dir is defined in the package MyTypes
required => 1,
coerce => 1,
);

Related

Is this a correct (intended) usage of MooseX::Getopt?

Is this a correct (intended) use of MooseX::Getopt? The documentation doesn't have a lot of examples. The code works, but I don't know if this was the intended usage model.
package AppOpt {
use Moose;
use Moose::Util::TypeConstraints;
use namespace::autoclean;
with 'MooseX::Getopt';
enum 'ReportType', [qw( activityByEvent activityByDate final )];
enum 'FormatType', [qw( text pretty html )];
has report => ( is => 'ro', isa => 'Str', required => 1 );
has verbose => ( is => 'ro', isa => 'Bool', default => 0 );
has format => ( is => 'ro', isa => 'Str', default => "text" );
__PACKAGE__->meta->make_immutable;
}
package main;
use strict;
use warnings;
my $opt = AppOpt->new_with_options();
printf("original \#ARGV = [%s]\n\n", join(' ', #ARGV));
# Please ignore this tasteless inspection of the object guts. -E
for my $k (keys(%{$opt})) {
unless($k =~ /(usage|ARGV|extra_argv)/) {
printf("%s => %s\n", $k, $$opt{$k});
}
}
exit(0);
Specifically: Are the options intended to be their own Class? I can't be sure from the docs.
Also, would it be appropriate to use BUILD to further validate the options?
This may sound like more than one question, but I don't mean it to be. I've run with other modules before only to find that I misunderstood how they were intended to be used.
The role MooseX::Getopt sets up command line options for attributes (except for those starting with _) of the class it is used with (consumed by). It is not intended to be "used" on its own.
So you write a class AppOpt, with attribute report, and when you include MooseX::Getopt role you can call the program with --report..., where option details are set by inferring as much as possible about the attribute from its class. That's it. You get command-line options.
A few accessors are provided, that one can use to inspect what happened on the command line, listed in your regex. But use them as accessors (methods), not by directly poking at the object.

Read only attributes being filled without writer method in Moose

I'm using Moose to create an object oriented class in Perl.
I have a number of attributes which I want to be read only which I've declared like this:
package BioIO::SeqIO;
use Moose;
use namespace::autoclean;
use MooseX::StrictConstructor;
use MooseX::Types::Moose qw(ArrayRef HashRef Int Str);
use FinalTypes::MyTypes qw(FileType);
has '_gi' => (isa => ArrayRef,
is => 'ro',
init_arg => undef,
writer => '_writer_gi');
I also have a BUILDER method which looks like this:
sub BUILD {
# Confessing with usage string if incorrect number of arguments used.
#_ == 2 or confess getErrorString4WrongNumberArguments();
# Initializing local variable with subroutine input.
my ($self) = #_;
# Creating BioIO::SeqIO object for GenBank or FASTA file.
$self->fileType =~ /genbank/i ? $self->_getGenbankSeqs() : $self->_getFastaSeqs();
}
My code works fine, however, I get a warning with the following test:
dies_ok {BioIO::SeqIO->new(filename => $fileNameIn, fileType => 'fasta', => _gi => [])} '... dies when _gi sent to BioIO::SeqIO constructor';
Here is the warning:
Use of uninitialized value $gi in hash element at BioIO/SeqIO.pm line 256, <$fh> chunk 1.
Lastly, here is line 256 for that error:
$hashDef{$gi} = $def;
I think that I'm getting a warning because the program is not dying as soon as the user attempts to write to _gi, however, I don't know how to ensure this happens?
In the attribute definition, note that the init_arg is set to undef, i.e. deleted:
has '_gi' => (isa => ArrayRef,
is => 'ro',
init_arg => undef,
writer => '_writer_gi');
The init arg is the name of the argument in the constructor call. As it is set to undef, you cannot initialize it via the constructor, but only via the writer method (here, an internal method called _writer_gi is created).

Moose: type libraries (MooseX::Types)

I am trying to figure out the proper way to incorporate Moose in my project. Here I found an article suggesting that Moose types should be organized in type libraries, which seems like a good idea. So I wrote the following code basing on the provided example:
file 1: MyTypeLib.pm
package MyTypeLib;
use MooseX::Types -declare => [ qw( MyStatus ) ];
use MooseX::Types::Moose qw/Int/;
subtype MyStatus,
as Int,
where { $_ >= 0 && $_ < 10 },
message { "Wrong status: $_" };
1;
file 2: MyTest.pm
package MyTest;
use MyTypeLib qw( MyStatus );
use Moose;
has status => ( is => 'rw', isa => 'MyStatus' );
no Moose; 1;
file 3: MyMain.pl
use strict;
use warnings;
use MyTest;
my $t1 = MyTest->new('status' => 5);
When I run it I get this message:
Attribute (status) does not pass the type constraint because:
Validation failed for 'MyStatus' with value 5 (not isa MyStatus) at
C:\Strawberry\perl\vendor\lib\Moose\Object.pm line 24
When I keep subtype definition in MyTest.pm and don't use MooseX::Types, everything works as expected. But the point is to move subtypes to a separate package and use them in other packages.
Could someone please advise how to make it work, or point to (or post) some working example, or suggest the alternative way of achieving the goal.
Thank you!
Remove the quotes: isa => MyStatus, not isa => 'MyStatus'. MyStatus is a constant-like function exported from your type library. Providing a string rather than a proper type constraint for isa ("stringy types") causes it to be looked up in Moose's type registry, or, if it's not found there, it's interpreted as the name of a class, and the type is inferred to be "any object of that class or its subclasses". Stringy types are less explicit and less flexible than using actual types, and more prone to conflicts since they all share a global namespace. It's best not to use them and type lbraries at the same time.
This seems to work
MyTypeLib.pm
package MyTypeLib;
use Moose::Util::TypeConstraints;
subtype MyStatus =>
as 'Num' =>
where { $_ >= 0 && $_ < 10 },
message { "Wrong status: $_" };
#coerce MyStatus => from Int => via { $_ };
1;
MyTest.pm
package MyTest;
use MyTypeLib;
use Moose;
has status => ( is => 'rw',
isa => 'MyStatus',
#coerce => 1 i
);
no Moose; 1;
MyMain.pl
use strict;
use warnings;
use MyTest;
use Data::Dumper;
my $t1 = MyTest->new( status => 5);
print Dumper $t1;
my $t2 = MyTest->new( status => 10);
Which gives
$ perl MyMain.pl
$VAR1 = bless( {
'status' => 5
}, 'MyTest' );
Attribute (status) does not pass the type constraint because: Wrong
status: 10 at /System/Library/Perl/Extras/5.18/darwin-thread-multi-
2level/Moose/Exception.pm line 37
There isn't much information on this aspect of Moose but it looks like Moose::Util::TypeConstraints is the MooseX module folded into Moose.
EDIT
Removed coerce!
You also need an explicit coercion.-

How to check the validity of the required argument in Moose constructor?

This is sure very simple question, but i'm still learning and not found the answer.
Need check the validity of the supplied (required) argument to Moose object constructor, e.g. like in the next example:
use 5.016;
use warnings;
package My {
use Moose;
has 'mydir' => (
is => 'ro',
isa => 'Str',
required => 1,
);
}
use File::Path qw(remove_tree);
package main {
my #dirs = qw(./d1 ./d2);
#ensure no one dir exists
remove_tree($_) for ( #dirs );
#create the first dir
mkdir $dirs[0] or die;
foreach my $dir( #dirs ) {
my $m = My->new( mydir=>$dir );
say "$dir ", defined($m) ? "" : "NOT", " ok";
}
}
The question is: what i should add to the My package to ensure create the My object only if the supplied mydir path exists? So somewhere need add the test if -d ... .
How to define the attribute mydir with validity check?
Wanted result of the main program:
./d1 ok
./d2 NOT ok
You can define a subtype with a type constraint.
The syntactic sugar for working with this is provided by Moose::Util::TypeConstraints.
package My;
use 5.16.0;
use Moose;
use Moose::Util::TypeConstraints; # provides sugar below
subtype 'ExistingDir' => (
as 'Str',
where { -d $_ },
message { 'The directory does not exist' }
);
has 'mydir' => (
is => 'ro',
isa => 'ExistingDir',
required => 1,
);
package main;
my $foo = My->new(mydir => 'perl'); # exists
say $foo->mydir();
my $bar = My->new(mydir => 'perlXXX'); # does not exist, so dies here...
outputs:
>mkdir perl
>perl foo.pl
perl
Attribute (mydir) does not pass the type constraint because: The directory does not exist at ...

Use a single module and get Moose plus several MooseX extensions

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.