2 package Moose::Meta::Role;
8 use Scalar::Util 'blessed';
10 use Devel::GlobalDestruction 'in_global_destruction';
12 our $VERSION = '1.00';
13 $VERSION = eval $VERSION;
14 our $AUTHORITY = 'cpan:STEVAN';
16 use Moose::Meta::Class;
17 use Moose::Meta::Role::Attribute;
18 use Moose::Meta::Role::Method;
19 use Moose::Meta::Role::Method::Required;
20 use Moose::Meta::Role::Method::Conflicting;
21 use Moose::Util qw( ensure_all_roles );
23 use base 'Class::MOP::Module', 'Class::MOP::Mixin::HasAttributes';
25 ## ------------------------------------------------------------------
27 ## I normally don't do this, but I am doing
28 ## a whole bunch of meta-programmin in this
29 ## module, so it just makes sense. For a clearer
30 ## picture of what is going on in the next
31 ## several lines of code, look at the really
32 ## big comment at the end of this file (right
35 ## ------------------------------------------------------------------
37 my $META = __PACKAGE__->meta;
39 ## ------------------------------------------------------------------
43 # since roles are lazy, we hold all the attributes
44 # of the individual role in 'statis' until which
45 # time when it is applied to a class. This means
46 # keeping a lot of things in hash maps, so we are
47 # using a little of that meta-programmin' magic
48 # here an saving lots of extra typin. And since
49 # many of these attributes above require similar
50 # functionality to support them, so we again use
51 # the wonders of meta-programmin' to deliver a
52 # very compact solution to this normally verbose
58 name => 'excluded_roles_map',
59 attr_reader => 'get_excluded_roles_map' ,
61 add => 'add_excluded_roles',
62 get_keys => 'get_excluded_roles_list',
63 existence => 'excludes_role',
67 name => 'required_methods',
68 attr_reader => 'get_required_methods_map',
70 remove => 'remove_required_methods',
71 get_values => 'get_required_method_list',
72 existence => 'requires_method',
77 my $attr_reader = $action->{attr_reader};
78 my $methods = $action->{methods};
80 # create the attribute
81 $META->add_attribute($action->{name} => (
82 reader => $attr_reader,
86 # create some helper methods
87 $META->add_method($methods->{add} => sub {
88 my ($self, @values) = @_;
89 $self->$attr_reader->{$_} = undef foreach @values;
90 }) if exists $methods->{add};
92 $META->add_method($methods->{get_keys} => sub {
94 keys %{$self->$attr_reader};
95 }) if exists $methods->{get_keys};
97 $META->add_method($methods->{get_values} => sub {
99 values %{$self->$attr_reader};
100 }) if exists $methods->{get_values};
102 $META->add_method($methods->{get} => sub {
103 my ($self, $name) = @_;
104 $self->$attr_reader->{$name}
105 }) if exists $methods->{get};
107 $META->add_method($methods->{existence} => sub {
108 my ($self, $name) = @_;
109 exists $self->$attr_reader->{$name} ? 1 : 0;
110 }) if exists $methods->{existence};
112 $META->add_method($methods->{remove} => sub {
113 my ($self, @values) = @_;
114 delete $self->$attr_reader->{$_} foreach @values;
115 }) if exists $methods->{remove};
118 $META->add_attribute(
120 reader => 'method_metaclass',
121 default => 'Moose::Meta::Role::Method',
124 $META->add_attribute(
125 'required_method_metaclass',
126 reader => 'required_method_metaclass',
127 default => 'Moose::Meta::Role::Method::Required',
130 $META->add_attribute(
131 'conflicting_method_metaclass',
132 reader => 'conflicting_method_metaclass',
133 default => 'Moose::Meta::Role::Method::Conflicting',
136 $META->add_attribute(
137 'application_to_class_class',
138 reader => 'application_to_class_class',
139 default => 'Moose::Meta::Role::Application::ToClass',
142 $META->add_attribute(
143 'application_to_role_class',
144 reader => 'application_to_role_class',
145 default => 'Moose::Meta::Role::Application::ToRole',
148 $META->add_attribute(
149 'application_to_instance_class',
150 reader => 'application_to_instance_class',
151 default => 'Moose::Meta::Role::Application::ToInstance',
154 # More or less copied from Moose::Meta::Class
158 return Class::MOP::get_metaclass_by_name($pkg)
159 || $class->SUPER::initialize(
161 'attribute_metaclass' => 'Moose::Meta::Role::Attribute',
170 my $meta = blessed $pkg ? $pkg : Class::MOP::class_of($pkg);
172 my %existing_classes;
174 %existing_classes = map { $_ => $meta->$_() } qw(
177 wrapped_method_metaclass
178 required_method_metaclass
179 conflicting_method_metaclass
180 application_to_class_class
181 application_to_role_class
182 application_to_instance_class
186 return $self->SUPER::reinitialize(
196 if (blessed $_[0] && ! $_[0]->isa('Moose::Meta::Role::Attribute') ) {
197 my $class = ref $_[0];
198 Moose->throw_error( "Cannot add a $class as an attribute to a role" );
201 return $self->SUPER::add_attribute(@_);
204 sub _attach_attribute {
205 my ( $self, $attribute ) = @_;
207 $attribute->attach_to_role($self);
210 sub add_required_methods {
215 if (!blessed($method)) {
216 $method = $self->required_method_metaclass->new(
220 $self->get_required_methods_map->{$method->name} = $method;
224 sub add_conflicting_method {
228 if (@_ == 1 && blessed($_[0])) {
232 $method = $self->conflicting_method_metaclass->new(@_);
235 $self->add_required_methods($method);
238 ## ------------------------------------------------------------------
242 # the before/around/after method modifiers are
243 # stored by name, but there can be many methods
244 # then associated with that name. So again we have
245 # lots of similar functionality, so we can do some
246 # meta-programmin' and save some time.
249 foreach my $modifier_type (qw[ before around after ]) {
251 my $attr_reader = "get_${modifier_type}_method_modifiers_map";
253 # create the attribute ...
254 $META->add_attribute("${modifier_type}_method_modifiers" => (
255 reader => $attr_reader,
256 default => sub { {} }
259 # and some helper methods ...
260 $META->add_method("get_${modifier_type}_method_modifiers" => sub {
261 my ($self, $method_name) = @_;
262 #return () unless exists $self->$attr_reader->{$method_name};
263 my $mm = $self->$attr_reader->{$method_name};
267 $META->add_method("has_${modifier_type}_method_modifiers" => sub {
268 my ($self, $method_name) = @_;
270 # for now we assume that if it exists,..
271 # it has at least one modifier in it
272 (exists $self->$attr_reader->{$method_name}) ? 1 : 0;
275 $META->add_method("add_${modifier_type}_method_modifier" => sub {
276 my ($self, $method_name, $method) = @_;
278 $self->$attr_reader->{$method_name} = []
279 unless exists $self->$attr_reader->{$method_name};
281 my $modifiers = $self->$attr_reader->{$method_name};
284 # check to see that we aren't adding the
285 # same code twice. We err in favor of the
286 # first on here, this may not be as expected
287 foreach my $modifier (@{$modifiers}) {
288 return if $modifier == $method;
291 push @{$modifiers} => $method;
296 ## ------------------------------------------------------------------
297 ## override method mofidiers
299 $META->add_attribute('override_method_modifiers' => (
300 reader => 'get_override_method_modifiers_map',
301 default => sub { {} }
305 # these are a little different because there
306 # can only be one per name, whereas the other
307 # method modifiers can have multiples.
310 sub add_override_method_modifier {
311 my ($self, $method_name, $method) = @_;
312 (!$self->has_method($method_name))
313 || Moose->throw_error("Cannot add an override of method '$method_name' " .
314 "because there is a local version of '$method_name'");
315 $self->get_override_method_modifiers_map->{$method_name} = $method;
318 sub has_override_method_modifier {
319 my ($self, $method_name) = @_;
321 # for now we assume that if it exists,..
322 # it has at least one modifier in it
323 (exists $self->get_override_method_modifiers_map->{$method_name}) ? 1 : 0;
326 sub get_override_method_modifier {
327 my ($self, $method_name) = @_;
328 $self->get_override_method_modifiers_map->{$method_name};
331 ## general list accessor ...
333 sub get_method_modifier_list {
334 my ($self, $modifier_type) = @_;
335 my $accessor = "get_${modifier_type}_method_modifiers_map";
336 keys %{$self->$accessor};
339 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
340 sub update_package_cache_flag {
342 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
347 ## ------------------------------------------------------------------
350 $META->add_attribute('roles' => (
351 reader => 'get_roles',
352 default => sub { [] }
356 my ($self, $role) = @_;
357 (blessed($role) && $role->isa('Moose::Meta::Role'))
358 || Moose->throw_error("Roles must be instances of Moose::Meta::Role");
359 push @{$self->get_roles} => $role;
360 $self->reset_package_cache_flag;
363 sub calculate_all_roles {
369 $_->calculate_all_roles
370 } @{ $self->get_roles });
374 my ($self, $role) = @_;
376 || Moose->throw_error("You must supply a role name to look for");
377 my $role_name = blessed $role ? $role->name : $role;
378 # if we are it,.. then return true
379 return 1 if $role_name eq $self->name;
380 # otherwise.. check our children
381 foreach my $role (@{$self->get_roles}) {
382 return 1 if $role->does_role($role_name);
387 sub find_method_by_name { (shift)->get_method(@_) }
390 Carp::cluck("The alias_method method is deprecated. Use add_method instead.\n");
394 $self->add_method(@_);
397 ## ------------------------------------------------------------------
399 ## ------------------------------------------------------------------
402 my ($self, $other, @args) = @_;
405 || Moose->throw_error("You must pass in an blessed instance");
407 my $application_class;
408 if ($other->isa('Moose::Meta::Role')) {
409 $application_class = $self->application_to_role_class;
411 elsif ($other->isa('Moose::Meta::Class')) {
412 $application_class = $self->application_to_class_class;
415 $application_class = $self->application_to_instance_class;
418 Class::MOP::load_class($application_class);
419 return $application_class->new(@args)->apply($self, $other);
422 sub composition_class_roles { }
425 my ($class, @role_specs) = @_;
427 require Moose::Meta::Role::Composite;
429 my (@roles, %role_params);
430 while (@role_specs) {
431 my ($role, $params) = @{ splice @role_specs, 0, 1 };
435 : Class::MOP::class_of($role);
437 my $actual_role = $requested_role->_role_for_combination($params);
438 push @roles => $actual_role;
440 next unless defined $params;
441 $role_params{$actual_role->name} = $params;
444 my $c = Moose::Meta::Role::Composite->new(roles => \@roles);
445 return $c->apply_params(\%role_params);
448 sub _role_for_combination {
449 my ($self, $params) = @_;
454 my ( $role, $package_name, %options ) = @_;
456 $options{package} = $package_name;
458 (ref $options{attributes} eq 'HASH')
459 || confess "You must pass a HASH ref of attributes"
460 if exists $options{attributes};
462 (ref $options{methods} eq 'HASH')
463 || confess "You must pass a HASH ref of methods"
464 if exists $options{methods};
466 my (%initialize_options) = %options;
467 delete @initialize_options{qw(
475 my $meta = $role->initialize( $package_name => %initialize_options );
477 $meta->_instantiate_module( $options{version}, $options{authority} );
480 $meta->add_method('meta' => sub {
481 $role->initialize(ref($_[0]) || $_[0]);
484 if (exists $options{attributes}) {
485 foreach my $attribute_name (keys %{$options{attributes}}) {
486 my $attr = $options{attributes}->{$attribute_name};
487 $meta->add_attribute(
488 $attribute_name => blessed $attr ? $attr : %{$attr} );
492 if (exists $options{methods}) {
493 foreach my $method_name (keys %{$options{methods}}) {
494 $meta->add_method($method_name, $options{methods}->{$method_name});
498 Class::MOP::weaken_metaclass($meta->name)
499 if $meta->is_anon_role;
504 # anonymous roles. most of it is copied straight out of Class::MOP::Class.
505 # an intrepid hacker might find great riches if he unifies this code with that
506 # code in Class::MOP::Module or Class::MOP::Package
509 # this should be sufficient, if you have a
510 # use case where it is not, write a test and
512 my $ANON_ROLE_SERIAL = 0;
515 # we need a sufficiently annoying prefix
516 # this should suffice for now, this is
517 # used in a couple of places below, so
518 # need to put it up here for now.
519 my $ANON_ROLE_PREFIX = 'Moose::Meta::Role::__ANON__::SERIAL::';
523 no warnings 'uninitialized';
524 $self->name =~ /^$ANON_ROLE_PREFIX/;
527 sub create_anon_role {
528 my ($role, %options) = @_;
529 my $package_name = $ANON_ROLE_PREFIX . ++$ANON_ROLE_SERIAL;
530 return $role->create($package_name, %options);
534 # this will only get called for
535 # anon-roles, all other calls
536 # are assumed to occur during
537 # global destruction and so don't
538 # really need to be handled explicitly
542 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
544 no warnings 'uninitialized';
545 return unless $self->name =~ /^$ANON_ROLE_PREFIX/;
547 # XXX: is this necessary for us? I don't understand what it's doing
550 # Moose does a weird thing where it replaces the metaclass for
551 # class when fixing metaclass incompatibility. In that case,
552 # we don't want to clean out the namespace now. We can detect
553 # that because Moose will explicitly update the singleton
554 # cache in Class::MOP.
555 #my $current_meta = Class::MOP::get_metaclass_by_name($self->name);
556 #return if $current_meta ne $self;
558 my ($serial_id) = ($self->name =~ /^$ANON_ROLE_PREFIX(\d+)/);
560 foreach my $key (keys %{$ANON_ROLE_PREFIX . $serial_id}) {
561 delete ${$ANON_ROLE_PREFIX . $serial_id}{$key};
563 delete ${'main::' . $ANON_ROLE_PREFIX}{$serial_id . '::'};
567 #####################################################################
569 ## This is Moose::Meta::Role as defined by Moose (plus the use of
570 ## MooseX::AttributeHelpers module). It is here as a reference to
571 ## make it easier to see what is happening above with all the meta
573 #####################################################################
576 # metaclass => 'Array',
577 # reader => 'get_roles',
578 # isa => 'ArrayRef[Moose::Meta::Role]',
579 # default => sub { [] },
581 # 'push' => 'add_role',
585 # has 'excluded_roles_map' => (
586 # metaclass => 'Hash',
587 # reader => 'get_excluded_roles_map',
588 # isa => 'HashRef[Str]',
590 # # Not exactly set, cause it sets multiple
591 # 'set' => 'add_excluded_roles',
592 # 'keys' => 'get_excluded_roles_list',
593 # 'exists' => 'excludes_role',
597 # has 'required_methods' => (
598 # metaclass => 'Hash',
599 # reader => 'get_required_methods_map',
600 # isa => 'HashRef[Moose::Meta::Role::Method::Required]',
602 # # not exactly set, or delete since it works for multiple
603 # 'set' => 'add_required_methods',
604 # 'delete' => 'remove_required_methods',
605 # 'keys' => 'get_required_method_list',
606 # 'exists' => 'requires_method',
610 # # the before, around and after modifiers are
611 # # HASH keyed by method-name, with ARRAY of
612 # # CODE refs to apply in that order
614 # has 'before_method_modifiers' => (
615 # metaclass => 'Hash',
616 # reader => 'get_before_method_modifiers_map',
617 # isa => 'HashRef[ArrayRef[CodeRef]]',
619 # 'keys' => 'get_before_method_modifiers',
620 # 'exists' => 'has_before_method_modifiers',
621 # # This actually makes sure there is an
622 # # ARRAY at the given key, and pushed onto
623 # # it. It also checks for duplicates as well
624 # # 'add' => 'add_before_method_modifier'
628 # has 'after_method_modifiers' => (
629 # metaclass => 'Hash',
630 # reader =>'get_after_method_modifiers_map',
631 # isa => 'HashRef[ArrayRef[CodeRef]]',
633 # 'keys' => 'get_after_method_modifiers',
634 # 'exists' => 'has_after_method_modifiers',
635 # # This actually makes sure there is an
636 # # ARRAY at the given key, and pushed onto
637 # # it. It also checks for duplicates as well
638 # # 'add' => 'add_after_method_modifier'
642 # has 'around_method_modifiers' => (
643 # metaclass => 'Hash',
644 # reader =>'get_around_method_modifiers_map',
645 # isa => 'HashRef[ArrayRef[CodeRef]]',
647 # 'keys' => 'get_around_method_modifiers',
648 # 'exists' => 'has_around_method_modifiers',
649 # # This actually makes sure there is an
650 # # ARRAY at the given key, and pushed onto
651 # # it. It also checks for duplicates as well
652 # # 'add' => 'add_around_method_modifier'
656 # # override is similar to the other modifiers
657 # # except that it is not an ARRAY of code refs
658 # # but instead just a single name->code mapping
660 # has 'override_method_modifiers' => (
661 # metaclass => 'Hash',
662 # reader =>'get_override_method_modifiers_map',
663 # isa => 'HashRef[CodeRef]',
665 # 'keys' => 'get_override_method_modifier',
666 # 'exists' => 'has_override_method_modifier',
667 # 'add' => 'add_override_method_modifier', # checks for local method ..
671 #####################################################################
682 Moose::Meta::Role - The Moose Role metaclass
686 This class is a subclass of L<Class::MOP::Module> that provides
687 additional Moose-specific functionality.
689 It's API looks a lot like L<Moose::Meta::Class>, but internally it
690 implements many things differently. This may change in the future.
694 C<Moose::Meta::Role> is a subclass of L<Class::MOP::Module>.
702 =item B<< Moose::Meta::Role->initialize($role_name) >>
704 This method creates a new role object with the provided name.
706 =item B<< Moose::Meta::Role->combine( [ $role => { ... } ], [ $role ], ... ) >>
708 This method accepts a list of array references. Each array reference
709 should contain a role name or L<Moose::Meta::Role> object as its first element. The second element is
710 an optional hash reference. The hash reference can contain C<-excludes>
711 and C<-alias> keys to control how methods are composed from the role.
713 The return value is a new L<Moose::Meta::Role::Composite> that
714 represents the combined roles.
716 =item B<< $metarole->composition_class_roles >>
718 When combining multiple roles using C<combine>, this method is used to obtain a
719 list of role names to be applied to the L<Moose::Meta::Role::Composite>
720 instance returned by C<combine>. The default implementation returns an empty
721 list. Extensions that need to hook into role combination may wrap this method
722 to return additional role names.
724 =item B<< Moose::Meta::Role->create($name, %options) >>
726 This method is identical to the L<Moose::Meta::Class> C<create>
729 =item B<< Moose::Meta::Role->create_anon_role >>
731 This method is identical to the L<Moose::Meta::Class>
732 C<create_anon_class> method.
734 =item B<< $metarole->is_anon_role >>
736 Returns true if the role is an anonymous role.
740 =head2 Role application
744 =item B<< $metarole->apply( $thing, @options ) >>
746 This method applies a role to the given C<$thing>. That can be another
747 L<Moose::Meta::Role>, object, a L<Moose::Meta::Class> object, or a
748 (non-meta) object instance.
750 The options are passed directly to the constructor for the appropriate
751 L<Moose::Meta::Role::Application> subclass.
753 Note that this will apply the role even if the C<$thing> in question already
754 C<does> this role. L<Moose::Util/does_role> is a convenient wrapper for
755 finding out if role application is necessary.
759 =head2 Roles and other roles
763 =item B<< $metarole->get_roles >>
765 This returns an array reference of roles which this role does. This
766 list may include duplicates.
768 =item B<< $metarole->calculate_all_roles >>
770 This returns a I<unique> list of all roles that this role does, and
771 all the roles that its roles do.
773 =item B<< $metarole->does_role($role) >>
775 Given a role I<name> or L<Moose::Meta::Role> object, returns true if this role
778 =item B<< $metarole->add_role($role) >>
780 Given a L<Moose::Meta::Role> object, this adds the role to the list of
781 roles that the role does.
783 =item B<< $metarole->get_excluded_roles_list >>
785 Returns a list of role names which this role excludes.
787 =item B<< $metarole->excludes_role($role_name) >>
789 Given a role I<name>, returns true if this role excludes the named
792 =item B<< $metarole->add_excluded_roles(@role_names) >>
794 Given one or more role names, adds those roles to the list of excluded
801 The methods for dealing with a role's methods are all identical in API
802 and behavior to the same methods in L<Class::MOP::Class>.
806 =item B<< $metarole->method_metaclass >>
808 Returns the method metaclass name for the role. This defaults to
809 L<Moose::Meta::Role::Method>.
811 =item B<< $metarole->get_method($name) >>
813 =item B<< $metarole->has_method($name) >>
815 =item B<< $metarole->add_method( $name, $body ) >>
817 =item B<< $metarole->get_method_list >>
819 =item B<< $metarole->find_method_by_name($name) >>
821 These methods are all identical to the methods of the same name in
822 L<Class::MOP::Package>
828 As with methods, the methods for dealing with a role's attribute are
829 all identical in API and behavior to the same methods in
830 L<Class::MOP::Class>.
832 However, attributes stored in this class are I<not> stored as
833 objects. Rather, the attribute definition is stored as a hash
834 reference. When a role is composed into a class, this hash reference
835 is passed directly to the metaclass's C<add_attribute> method.
837 This is quite likely to change in the future.
841 =item B<< $metarole->get_attribute($attribute_name) >>
843 =item B<< $metarole->has_attribute($attribute_name) >>
845 =item B<< $metarole->get_attribute_list >>
847 =item B<< $metarole->add_attribute($name, %options) >>
849 =item B<< $metarole->remove_attribute($attribute_name) >>
853 =head2 Required methods
857 =item B<< $metarole->get_required_method_list >>
859 Returns the list of methods required by the role.
861 =item B<< $metarole->requires_method($name) >>
863 Returns true if the role requires the named method.
865 =item B<< $metarole->add_required_methods(@names) >>
867 Adds the named methods to the role's list of required methods.
869 =item B<< $metarole->remove_required_methods(@names) >>
871 Removes the named methods from the role's list of required methods.
873 =item B<< $metarole->add_conflicting_method(%params) >>
875 Instantiate the parameters as a L<Moose::Meta::Role::Method::Conflicting>
876 object, then add it to the required method list.
880 =head2 Method modifiers
882 These methods act like their counterparts in L<Class::MOP::Class> and
883 L<Moose::Meta::Class>.
885 However, method modifiers are simply stored internally, and are not
886 applied until the role itself is applied to a class.
890 =item B<< $metarole->add_after_method_modifier($method_name, $method) >>
892 =item B<< $metarole->add_around_method_modifier($method_name, $method) >>
894 =item B<< $metarole->add_before_method_modifier($method_name, $method) >>
896 =item B<< $metarole->add_override_method_modifier($method_name, $method) >>
898 These methods all add an appropriate modifier to the internal list of
901 =item B<< $metarole->has_after_method_modifiers >>
903 =item B<< $metarole->has_around_method_modifiers >>
905 =item B<< $metarole->has_before_method_modifiers >>
907 =item B<< $metarole->has_override_method_modifier >>
909 Return true if the role has any modifiers of the given type.
911 =item B<< $metarole->get_after_method_modifiers($method_name) >>
913 =item B<< $metarole->get_around_method_modifiers($method_name) >>
915 =item B<< $metarole->get_before_method_modifiers($method_name) >>
917 Given a method name, returns a list of the appropriate modifiers for
920 =item B<< $metarole->get_override_method_modifier($method_name) >>
922 Given a method name, returns the override method modifier for that
923 method, if it has one.
931 =item B<< Moose::Meta::Role->meta >>
933 This will return a L<Class::MOP::Class> instance for this class.
939 See L<Moose/BUGS> for details on reporting bugs.
943 Stevan Little E<lt>stevan@iinteractive.comE<gt>
945 =head1 COPYRIGHT AND LICENSE
947 Copyright 2006-2010 by Infinity Interactive, Inc.
949 L<http://www.iinteractive.com>
951 This library is free software; you can redistribute it and/or modify
952 it under the same terms as Perl itself.