2 package Moose::Meta::Role;
8 use Scalar::Util 'blessed';
10 use Sub::Name 'subname';
11 use Devel::GlobalDestruction 'in_global_destruction';
13 our $VERSION = '0.92';
14 $VERSION = eval $VERSION;
15 our $AUTHORITY = 'cpan:STEVAN';
17 use Moose::Meta::Class;
18 use Moose::Meta::Role::Method;
19 use Moose::Meta::Role::Method::Required;
20 use Moose::Meta::Role::Method::Conflicting;
22 use base 'Class::MOP::Module';
24 ## ------------------------------------------------------------------
26 ## I normally don't do this, but I am doing
27 ## a whole bunch of meta-programmin in this
28 ## module, so it just makes sense. For a clearer
29 ## picture of what is going on in the next
30 ## several lines of code, look at the really
31 ## big comment at the end of this file (right
34 ## ------------------------------------------------------------------
36 my $META = __PACKAGE__->meta;
38 ## ------------------------------------------------------------------
42 # since roles are lazy, we hold all the attributes
43 # of the individual role in 'statis' until which
44 # time when it is applied to a class. This means
45 # keeping a lot of things in hash maps, so we are
46 # using a little of that meta-programmin' magic
47 # here an saving lots of extra typin. And since
48 # many of these attributes above require similar
49 # functionality to support them, so we again use
50 # the wonders of meta-programmin' to deliver a
51 # very compact solution to this normally verbose
57 name => 'excluded_roles_map',
58 attr_reader => 'get_excluded_roles_map' ,
60 add => 'add_excluded_roles',
61 get_keys => 'get_excluded_roles_list',
62 existence => 'excludes_role',
66 name => 'required_methods',
67 attr_reader => 'get_required_methods_map',
69 remove => 'remove_required_methods',
70 get_values => 'get_required_method_list',
71 existence => 'requires_method',
75 name => 'attribute_map',
76 attr_reader => 'get_attribute_map',
78 get => 'get_attribute',
79 get_keys => 'get_attribute_list',
80 existence => 'has_attribute',
81 remove => 'remove_attribute',
86 my $attr_reader = $action->{attr_reader};
87 my $methods = $action->{methods};
89 # create the attribute
90 $META->add_attribute($action->{name} => (
91 reader => $attr_reader,
95 # create some helper methods
96 $META->add_method($methods->{add} => sub {
97 my ($self, @values) = @_;
98 $self->$attr_reader->{$_} = undef foreach @values;
99 }) if exists $methods->{add};
101 $META->add_method($methods->{get_keys} => sub {
103 keys %{$self->$attr_reader};
104 }) if exists $methods->{get_keys};
106 $META->add_method($methods->{get_values} => sub {
108 values %{$self->$attr_reader};
109 }) if exists $methods->{get_values};
111 $META->add_method($methods->{get} => sub {
112 my ($self, $name) = @_;
113 $self->$attr_reader->{$name}
114 }) if exists $methods->{get};
116 $META->add_method($methods->{existence} => sub {
117 my ($self, $name) = @_;
118 exists $self->$attr_reader->{$name} ? 1 : 0;
119 }) if exists $methods->{existence};
121 $META->add_method($methods->{remove} => sub {
122 my ($self, @values) = @_;
123 delete $self->$attr_reader->{$_} foreach @values;
124 }) if exists $methods->{remove};
127 $META->add_attribute(
129 reader => 'method_metaclass',
130 default => 'Moose::Meta::Role::Method',
133 $META->add_attribute(
134 'required_method_metaclass',
135 reader => 'required_method_metaclass',
136 default => 'Moose::Meta::Role::Method::Required',
139 $META->add_attribute(
140 'conflicting_method_metaclass',
141 reader => 'conflicting_method_metaclass',
142 default => 'Moose::Meta::Role::Method::Conflicting',
145 $META->add_attribute(
146 'application_to_class_class',
147 reader => 'application_to_class_class',
148 default => 'Moose::Meta::Role::Application::ToClass',
151 $META->add_attribute(
152 'application_to_role_class',
153 reader => 'application_to_role_class',
154 default => 'Moose::Meta::Role::Application::ToRole',
157 $META->add_attribute(
158 'application_to_instance_class',
159 reader => 'application_to_instance_class',
160 default => 'Moose::Meta::Role::Application::ToInstance',
163 $META->add_attribute(
164 'composition_class_roles',
165 reader => 'composition_class_roles',
166 predicate => 'has_composition_class_roles',
169 ## some things don't always fit, so they go here ...
174 unless ( defined $name ) {
176 Moose->throw_error("You must provide a name for the attribute");
179 if (scalar @_ == 1 && ref($_[0]) eq 'HASH') {
185 $self->get_attribute_map->{$name} = $attr_desc;
188 sub add_required_methods {
193 if (!blessed($method)) {
194 $method = $self->required_method_metaclass->new(
198 $self->get_required_methods_map->{$method->name} = $method;
202 sub add_conflicting_method {
206 if (@_ == 1 && blessed($_[0])) {
210 $method = $self->conflicting_method_metaclass->new(@_);
213 $self->add_required_methods($method);
216 ## ------------------------------------------------------------------
220 # the before/around/after method modifiers are
221 # stored by name, but there can be many methods
222 # then associated with that name. So again we have
223 # lots of similar functionality, so we can do some
224 # meta-programmin' and save some time.
227 foreach my $modifier_type (qw[ before around after ]) {
229 my $attr_reader = "get_${modifier_type}_method_modifiers_map";
231 # create the attribute ...
232 $META->add_attribute("${modifier_type}_method_modifiers" => (
233 reader => $attr_reader,
234 default => sub { {} }
237 # and some helper methods ...
238 $META->add_method("get_${modifier_type}_method_modifiers" => sub {
239 my ($self, $method_name) = @_;
240 #return () unless exists $self->$attr_reader->{$method_name};
241 my $mm = $self->$attr_reader->{$method_name};
245 $META->add_method("has_${modifier_type}_method_modifiers" => sub {
246 my ($self, $method_name) = @_;
248 # for now we assume that if it exists,..
249 # it has at least one modifier in it
250 (exists $self->$attr_reader->{$method_name}) ? 1 : 0;
253 $META->add_method("add_${modifier_type}_method_modifier" => sub {
254 my ($self, $method_name, $method) = @_;
256 $self->$attr_reader->{$method_name} = []
257 unless exists $self->$attr_reader->{$method_name};
259 my $modifiers = $self->$attr_reader->{$method_name};
262 # check to see that we aren't adding the
263 # same code twice. We err in favor of the
264 # first on here, this may not be as expected
265 foreach my $modifier (@{$modifiers}) {
266 return if $modifier == $method;
269 push @{$modifiers} => $method;
274 ## ------------------------------------------------------------------
275 ## override method mofidiers
277 $META->add_attribute('override_method_modifiers' => (
278 reader => 'get_override_method_modifiers_map',
279 default => sub { {} }
283 # these are a little different because there
284 # can only be one per name, whereas the other
285 # method modifiers can have multiples.
288 sub add_override_method_modifier {
289 my ($self, $method_name, $method) = @_;
290 (!$self->has_method($method_name))
291 || Moose->throw_error("Cannot add an override of method '$method_name' " .
292 "because there is a local version of '$method_name'");
293 $self->get_override_method_modifiers_map->{$method_name} = $method;
296 sub has_override_method_modifier {
297 my ($self, $method_name) = @_;
299 # for now we assume that if it exists,..
300 # it has at least one modifier in it
301 (exists $self->get_override_method_modifiers_map->{$method_name}) ? 1 : 0;
304 sub get_override_method_modifier {
305 my ($self, $method_name) = @_;
306 $self->get_override_method_modifiers_map->{$method_name};
309 ## general list accessor ...
311 sub get_method_modifier_list {
312 my ($self, $modifier_type) = @_;
313 my $accessor = "get_${modifier_type}_method_modifiers_map";
314 keys %{$self->$accessor};
317 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
318 sub update_package_cache_flag {
320 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
325 ## ------------------------------------------------------------------
328 $META->add_attribute('roles' => (
329 reader => 'get_roles',
330 default => sub { [] }
334 my ($self, $role) = @_;
335 (blessed($role) && $role->isa('Moose::Meta::Role'))
336 || Moose->throw_error("Roles must be instances of Moose::Meta::Role");
337 push @{$self->get_roles} => $role;
338 $self->reset_package_cache_flag;
341 sub calculate_all_roles {
347 $_->calculate_all_roles
348 } @{ $self->get_roles });
352 my ($self, $role_name) = @_;
354 || Moose->throw_error("You must supply a role name to look for");
355 # if we are it,.. then return true
356 return 1 if $role_name eq $self->name;
357 # otherwise.. check our children
358 foreach my $role (@{$self->get_roles}) {
359 return 1 if $role->does_role($role_name);
364 sub find_method_by_name { (shift)->get_method(@_) }
367 Carp::cluck("The alias_method method is deprecated. Use add_method instead.\n");
371 $self->add_method(@_);
374 ## ------------------------------------------------------------------
376 ## ------------------------------------------------------------------
379 my ($self, $other, @args) = @_;
382 || Moose->throw_error("You must pass in an blessed instance");
384 my $application_class;
385 if ($other->isa('Moose::Meta::Role')) {
386 $application_class = $self->application_to_role_class;
388 elsif ($other->isa('Moose::Meta::Class')) {
389 $application_class = $self->application_to_class_class;
392 $application_class = $self->application_to_instance_class;
395 Class::MOP::load_class($application_class);
396 return $application_class->new(@args)->apply($self, $other);
400 my ($class, @role_specs) = @_;
402 require Moose::Meta::Role::Composite;
404 my (@roles, %role_params);
405 while (@role_specs) {
406 my ($role_name, $params) = @{ splice @role_specs, 0, 1 };
407 my $requested_role = Class::MOP::class_of($role_name);
409 my $actual_role = $requested_role->_role_for_combination($params);
410 push @roles => $actual_role;
412 next unless defined $params;
413 $role_params{$actual_role->name} = $params;
416 my $c = Moose::Meta::Role::Composite->new(roles => \@roles);
417 return $c->apply_params(\%role_params);
420 sub _role_for_combination {
421 my ($self, $params) = @_;
426 my ( $role, $package_name, %options ) = @_;
428 $options{package} = $package_name;
430 (ref $options{attributes} eq 'HASH')
431 || confess "You must pass a HASH ref of attributes"
432 if exists $options{attributes};
434 (ref $options{methods} eq 'HASH')
435 || confess "You must pass a HASH ref of methods"
436 if exists $options{methods};
438 my (%initialize_options) = %options;
439 delete @initialize_options{qw(
447 my $meta = $role->initialize( $package_name => %initialize_options );
449 $meta->_instantiate_module( $options{version}, $options{authority} );
452 $meta->add_method('meta' => sub {
453 $role->initialize(ref($_[0]) || $_[0]);
456 if (exists $options{attributes}) {
457 foreach my $attribute_name (keys %{$options{attributes}}) {
458 my $attr = $options{attributes}->{$attribute_name};
459 $meta->add_attribute($attribute_name => $attr);
463 if (exists $options{methods}) {
464 foreach my $method_name (keys %{$options{methods}}) {
465 $meta->add_method($method_name, $options{methods}->{$method_name});
469 Class::MOP::weaken_metaclass($meta->name)
470 if $meta->is_anon_role;
475 # anonymous roles. most of it is copied straight out of Class::MOP::Class.
476 # an intrepid hacker might find great riches if he unifies this code with that
477 # code in Class::MOP::Module or Class::MOP::Package
480 # this should be sufficient, if you have a
481 # use case where it is not, write a test and
483 my $ANON_ROLE_SERIAL = 0;
486 # we need a sufficiently annoying prefix
487 # this should suffice for now, this is
488 # used in a couple of places below, so
489 # need to put it up here for now.
490 my $ANON_ROLE_PREFIX = 'Moose::Meta::Role::__ANON__::SERIAL::';
494 no warnings 'uninitialized';
495 $self->name =~ /^$ANON_ROLE_PREFIX/;
498 sub create_anon_role {
499 my ($role, %options) = @_;
500 my $package_name = $ANON_ROLE_PREFIX . ++$ANON_ROLE_SERIAL;
501 return $role->create($package_name, %options);
505 # this will only get called for
506 # anon-roles, all other calls
507 # are assumed to occur during
508 # global destruction and so don't
509 # really need to be handled explicitly
513 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
515 no warnings 'uninitialized';
516 return unless $self->name =~ /^$ANON_ROLE_PREFIX/;
518 # XXX: is this necessary for us? I don't understand what it's doing
521 # Moose does a weird thing where it replaces the metaclass for
522 # class when fixing metaclass incompatibility. In that case,
523 # we don't want to clean out the namespace now. We can detect
524 # that because Moose will explicitly update the singleton
525 # cache in Class::MOP.
526 #my $current_meta = Class::MOP::get_metaclass_by_name($self->name);
527 #return if $current_meta ne $self;
529 my ($serial_id) = ($self->name =~ /^$ANON_ROLE_PREFIX(\d+)/);
531 foreach my $key (keys %{$ANON_ROLE_PREFIX . $serial_id}) {
532 delete ${$ANON_ROLE_PREFIX . $serial_id}{$key};
534 delete ${'main::' . $ANON_ROLE_PREFIX}{$serial_id . '::'};
538 #####################################################################
540 ## This is Moose::Meta::Role as defined by Moose (plus the use of
541 ## MooseX::AttributeHelpers module). It is here as a reference to
542 ## make it easier to see what is happening above with all the meta
544 #####################################################################
547 # metaclass => 'Array',
548 # reader => 'get_roles',
549 # isa => 'ArrayRef[Moose::Meta::Role]',
550 # default => sub { [] },
552 # 'push' => 'add_role',
556 # has 'excluded_roles_map' => (
557 # metaclass => 'Hash',
558 # reader => 'get_excluded_roles_map',
559 # isa => 'HashRef[Str]',
561 # # Not exactly set, cause it sets multiple
562 # 'set' => 'add_excluded_roles',
563 # 'keys' => 'get_excluded_roles_list',
564 # 'exists' => 'excludes_role',
568 # has 'attribute_map' => (
569 # metaclass => 'Hash',
570 # reader => 'get_attribute_map',
571 # isa => 'HashRef[Str]',
573 # # 'set' => 'add_attribute' # has some special crap in it
574 # 'get' => 'get_attribute',
575 # 'keys' => 'get_attribute_list',
576 # 'exists' => 'has_attribute',
577 # # Not exactly delete, cause it sets multiple
578 # 'delete' => 'remove_attribute',
582 # has 'required_methods' => (
583 # metaclass => 'Hash',
584 # reader => 'get_required_methods_map',
585 # isa => 'HashRef[Moose::Meta::Role::Method::Required]',
587 # # not exactly set, or delete since it works for multiple
588 # 'set' => 'add_required_methods',
589 # 'delete' => 'remove_required_methods',
590 # 'keys' => 'get_required_method_list',
591 # 'exists' => 'requires_method',
595 # # the before, around and after modifiers are
596 # # HASH keyed by method-name, with ARRAY of
597 # # CODE refs to apply in that order
599 # has 'before_method_modifiers' => (
600 # metaclass => 'Hash',
601 # reader => 'get_before_method_modifiers_map',
602 # isa => 'HashRef[ArrayRef[CodeRef]]',
604 # 'keys' => 'get_before_method_modifiers',
605 # 'exists' => 'has_before_method_modifiers',
606 # # This actually makes sure there is an
607 # # ARRAY at the given key, and pushed onto
608 # # it. It also checks for duplicates as well
609 # # 'add' => 'add_before_method_modifier'
613 # has 'after_method_modifiers' => (
614 # metaclass => 'Hash',
615 # reader =>'get_after_method_modifiers_map',
616 # isa => 'HashRef[ArrayRef[CodeRef]]',
618 # 'keys' => 'get_after_method_modifiers',
619 # 'exists' => 'has_after_method_modifiers',
620 # # This actually makes sure there is an
621 # # ARRAY at the given key, and pushed onto
622 # # it. It also checks for duplicates as well
623 # # 'add' => 'add_after_method_modifier'
627 # has 'around_method_modifiers' => (
628 # metaclass => 'Hash',
629 # reader =>'get_around_method_modifiers_map',
630 # isa => 'HashRef[ArrayRef[CodeRef]]',
632 # 'keys' => 'get_around_method_modifiers',
633 # 'exists' => 'has_around_method_modifiers',
634 # # This actually makes sure there is an
635 # # ARRAY at the given key, and pushed onto
636 # # it. It also checks for duplicates as well
637 # # 'add' => 'add_around_method_modifier'
641 # # override is similar to the other modifiers
642 # # except that it is not an ARRAY of code refs
643 # # but instead just a single name->code mapping
645 # has 'override_method_modifiers' => (
646 # metaclass => 'Hash',
647 # reader =>'get_override_method_modifiers_map',
648 # isa => 'HashRef[CodeRef]',
650 # 'keys' => 'get_override_method_modifier',
651 # 'exists' => 'has_override_method_modifier',
652 # 'add' => 'add_override_method_modifier', # checks for local method ..
656 #####################################################################
667 Moose::Meta::Role - The Moose Role metaclass
671 This class is a subclass of L<Class::MOP::Module> that provides
672 additional Moose-specific functionality.
674 It's API looks a lot like L<Moose::Meta::Class>, but internally it
675 implements many things differently. This may change in the future.
679 C<Moose::Meta::Role> is a subclass of L<Class::MOP::Module>.
687 =item B<< Moose::Meta::Role->initialize($role_name) >>
689 This method creates a new role object with the provided name.
691 =item B<< Moose::Meta::Role->combine( [ $role => { ... } ], [ $role ], ... ) >>
693 This method accepts a list of array references. Each array reference
694 should contain a role name as its first element. The second element is
695 an optional hash reference. The hash reference can contain C<-excludes>
696 and C<-alias> keys to control how methods are composed from the role.
698 The return value is a new L<Moose::Meta::Role::Composite> that
699 represents the combined roles.
701 =item B<< Moose::Meta::Role->create($name, %options) >>
703 This method is identical to the L<Moose::Meta::Class> C<create>
706 =item B<< Moose::Meta::Role->create_anon_role >>
708 This method is identical to the L<Moose::Meta::Class>
709 C<create_anon_class> method.
711 =item B<< $metarole->is_anon_role >>
713 Returns true if the role is an anonymous role.
717 =head2 Role application
721 =item B<< $metarole->apply( $thing, @options ) >>
723 This method applies a role to the given C<$thing>. That can be another
724 L<Moose::Meta::Role>, object, a L<Moose::Meta::Class> object, or a
725 (non-meta) object instance.
727 The options are passed directly to the constructor for the appropriate
728 L<Moose::Meta::Role::Application> subclass.
730 Note that this will apply the role even if the C<$thing> in question already
731 C<does> this role. L<Moose::Util/does_role> is a convenient wrapper for
732 finding out if role application is necessary.
736 =head2 Roles and other roles
740 =item B<< $metarole->get_roles >>
742 This returns an array reference of roles which this role does. This
743 list may include duplicates.
745 =item B<< $metarole->calculate_all_roles >>
747 This returns a I<unique> list of all roles that this role does, and
748 all the roles that its roles do.
750 =item B<< $metarole->does_role($role_name) >>
752 Given a role I<name>, returns true if this role does the given
755 =item B<< $metarole->add_role($role) >>
757 Given a L<Moose::Meta::Role> object, this adds the role to the list of
758 roles that the role does.
760 =item B<< $metarole->get_excluded_roles_list >>
762 Returns a list of role names which this role excludes.
764 =item B<< $metarole->excludes_role($role_name) >>
766 Given a role I<name>, returns true if this role excludes the named
769 =item B<< $metarole->add_excluded_roles(@role_names) >>
771 Given one or more role names, adds those roles to the list of excluded
778 The methods for dealing with a role's methods are all identical in API
779 and behavior to the same methods in L<Class::MOP::Class>.
783 =item B<< $metarole->method_metaclass >>
785 Returns the method metaclass name for the role. This defaults to
786 L<Moose::Meta::Role::Method>.
788 =item B<< $metarole->get_method($name) >>
790 =item B<< $metarole->has_method($name) >>
792 =item B<< $metarole->add_method( $name, $body ) >>
794 =item B<< $metarole->get_method_list >>
796 =item B<< $metarole->find_method_by_name($name) >>
798 These methods are all identical to the methods of the same name in
799 L<Class::MOP::Package>
805 As with methods, the methods for dealing with a role's attribute are
806 all identical in API and behavior to the same methods in
807 L<Class::MOP::Class>.
809 However, attributes stored in this class are I<not> stored as
810 objects. Rather, the attribute definition is stored as a hash
811 reference. When a role is composed into a class, this hash reference
812 is passed directly to the metaclass's C<add_attribute> method.
814 This is quite likely to change in the future.
818 =item B<< $metarole->get_attribute($attribute_name) >>
820 =item B<< $metarole->has_attribute($attribute_name) >>
822 =item B<< $metarole->get_attribute_map >>
824 =item B<< $metarole->get_attribute_list >>
826 =item B<< $metarole->add_attribute($name, %options) >>
828 =item B<< $metarole->remove_attribute($attribute_name) >>
832 =head2 Required methods
836 =item B<< $metarole->get_required_method_list >>
838 Returns the list of methods required by the role.
840 =item B<< $metarole->requires_method($name) >>
842 Returns true if the role requires the named method.
844 =item B<< $metarole->add_required_methods(@names) >>
846 Adds the named methods to the role's list of required methods.
848 =item B<< $metarole->remove_required_methods(@names) >>
850 Removes the named methods from the role's list of required methods.
852 =item B<< $metarole->add_conflicting_method(%params) >>
854 Instantiate the parameters as a L<Moose::Meta::Role::Method::Conflicting>
855 object, then add it to the required method list.
859 =head2 Method modifiers
861 These methods act like their counterparts in L<Class::Mop::Class> and
862 L<Moose::Meta::Class>.
864 However, method modifiers are simply stored internally, and are not
865 applied until the role itself is applied to a class.
869 =item B<< $metarole->add_after_method_modifier($method_name, $method) >>
871 =item B<< $metarole->add_around_method_modifier($method_name, $method) >>
873 =item B<< $metarole->add_before_method_modifier($method_name, $method) >>
875 =item B<< $metarole->add_override_method_modifier($method_name, $method) >>
877 These methods all add an appropriate modifier to the internal list of
880 =item B<< $metarole->has_after_method_modifiers >>
882 =item B<< $metarole->has_around_method_modifiers >>
884 =item B<< $metarole->has_before_method_modifiers >>
886 =item B<< $metarole->has_override_method_modifier >>
888 Return true if the role has any modifiers of the given type.
890 =item B<< $metarole->get_after_method_modifiers($method_name) >>
892 =item B<< $metarole->get_around_method_modifiers($method_name) >>
894 =item B<< $metarole->get_before_method_modifiers($method_name) >>
896 Given a method name, returns a list of the appropriate modifiers for
899 =item B<< $metarole->get_override_method_modifier($method_name) >>
901 Given a method name, returns the override method modifier for that
902 method, if it has one.
910 =item B<< Moose::Meta::Role->meta >>
912 This will return a L<Class::MOP::Class> instance for this class.
918 All complex software has bugs lurking in it, and this module is no
919 exception. If you find a bug please either email me, or add the bug
924 Stevan Little E<lt>stevan@iinteractive.comE<gt>
926 =head1 COPYRIGHT AND LICENSE
928 Copyright 2006-2009 by Infinity Interactive, Inc.
930 L<http://www.iinteractive.com>
932 This library is free software; you can redistribute it and/or modify
933 it under the same terms as Perl itself.