package Moose::Util;
use Exporter qw/import/;
-use Scalar::Util qw/blessed/;
+use Scalar::Util;
use strict;
use warnings;
our $AUTHORITY = 'cpan:BERLE';
-our @EXPORT_OK = qw/can_role search_class_by_role/;
+our @EXPORT_OK = qw/does_role search_class_by_role/;
-sub can_role {
- my ($class,$does) = @_;
+sub does_role {
+ my ($class, $role) = @_;
- return ((!ref $class && eval { $class->isa ('UNIVERSAL') }) || Scalar::Util::blessed ($class))
- && $class->can ('does')
- && $class->does ($does);
+ return unless defined $class;
+
+ my $meta = Class::MOP::get_metaclass_by_name (ref $class || $class);
+
+ return unless defined $meta;
+
+ return $meta->does_role ($role);
}
sub search_class_by_role {
use Moose::Util qw/can_role search_class_by_role/;
- if (can_role ($object,'rolename')) {
- print "The object can do rolename!\n";
+ if (does_role($object, $role)) {
+ print "The object can do $role!\n";
}
my $class = search_class_by_role($object, 'FooRole');
=over 4
-=item can_role
+=item does_role
- can_role ($object,$rolename);
+ does_role($object, $rolename);
Returns true if $object can do the role $rolename.
package Test::Moose;
use Exporter;
-use Moose::Util qw/can_role/;
+use Moose::Util qw/does_role/;
use Test::Builder;
use strict;
sub does_ok ($$;$) {
my ($class,$does,$name) = @_;
- return $tester->ok (can_role ($class,$does),$name)
+ return $tester->ok (does_role ($class,$does),$name)
}
1;
--- /dev/null
+#!/usr/bin/env perl
+
+use Test::More tests => 9;
+
+use strict;
+use warnings;
+
+BEGIN {
+ use_ok('Moose');
+ use_ok('Moose::Role');
+ use_ok('Moose::Util');
+}
+
+{
+ package Foo;
+
+ use Moose::Role;
+}
+
+{
+ package Bar;
+
+ use Moose;
+
+ with qw/Foo/;
+}
+
+{
+ package Baz;
+
+ use Moose;
+}
+
+# Classes
+
+ok(Moose::Util::does_role('Bar', 'Foo'));
+
+ok(! Moose::Util::does_role('Baz', 'Foo'));
+
+# Objects
+
+my $bar = Bar->new;
+
+ok(Moose::Util::does_role($bar, 'Foo'));
+
+my $baz = Baz->new;
+
+ok(! Moose::Util::does_role($baz, 'Foo'));
+
+# Invalid values
+
+ok(! Moose::Util::does_role(undef,'Foo'));
+
+ok(! Moose::Util::does_role(1,'Foo'));
+