Skip to content

Instantly share code, notes, and snippets.

@j1n3l0
Created June 16, 2010 15:53
Show Gist options
  • Save j1n3l0/440879 to your computer and use it in GitHub Desktop.
Save j1n3l0/440879 to your computer and use it in GitHub Desktop.
HowTo: ensure values in your hash of objects are objects [perl,moose,typeconstraints]
#!/usr/bin/env perl
use Modern::Perl;
use Test::Most;
my @not_objects
= ( [ 'array', 'ref' ], { 'hash' => 'ref' }, \'string ref', 'string', 1 );
ANY: {
{
package Foo::Accepts::Any;
use Moose;
has 'bar' => (
'traits' => ['Hash'],
'default' => sub { {} },
'isa' => 'HashRef[Any]',
'handles' => { 'set_bar' => 'set' },
);
}
my $foo = Foo::Accepts::Any->new();
lives_ok { $foo->set_bar( 'some_key' => Moose::Object->new() ) }
'Foo::Accepts::Any::set_bar accepts objects';
for my $item (@not_objects) {
lives_ok { $foo->set_bar( 'some_key' => $item ) }
'Foo::Accepts::Any::set_bar accepts ' . ( ref $item || $item );
}
}
OBJECT: {
{
package Foo::Accepts::Object;
use Moose;
has 'bar' => (
'traits' => ['Hash'],
'default' => sub { {} },
'isa' => 'HashRef[Object]',
'handles' => { 'set_bar' => 'set' },
);
}
my $foo = Foo::Accepts::Object->new();
lives_ok { $foo->set_bar( 'some_key' => Moose::Object->new() ) }
'Foo::Accepts::Object::set_bar accepts objects';
for my $item (@not_objects) {
dies_ok { $foo->set_bar( 'some_key' => $item ) }
'Foo::Accepts::Object::set_bar does not accept ' . ( ref $item || $item );
}
}
done_testing();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment