2 package Moose::Meta::Role;
8 use Scalar::Util 'blessed';
10 use Devel::GlobalDestruction 'in_global_destruction';
12 our $VERSION = '0.92';
13 $VERSION = eval $VERSION;
14 our $AUTHORITY = 'cpan:STEVAN';
16 use Moose::Meta::Class;
17 use Moose::Meta::Role::Method;
18 use Moose::Meta::Role::Method::Required;
19 use Moose::Meta::Role::Method::Conflicting;
21 use base 'Class::MOP::Module';
23 ## ------------------------------------------------------------------
25 ## I normally don't do this, but I am doing
26 ## a whole bunch of meta-programmin in this
27 ## module, so it just makes sense. For a clearer
28 ## picture of what is going on in the next
29 ## several lines of code, look at the really
30 ## big comment at the end of this file (right
33 ## ------------------------------------------------------------------
35 my $META = __PACKAGE__->meta;
37 ## ------------------------------------------------------------------
41 # since roles are lazy, we hold all the attributes
42 # of the individual role in 'statis' until which
43 # time when it is applied to a class. This means
44 # keeping a lot of things in hash maps, so we are
45 # using a little of that meta-programmin' magic
46 # here an saving lots of extra typin. And since
47 # many of these attributes above require similar
48 # functionality to support them, so we again use
49 # the wonders of meta-programmin' to deliver a
50 # very compact solution to this normally verbose
56 name => 'excluded_roles_map',
57 attr_reader => 'get_excluded_roles_map' ,
59 add => 'add_excluded_roles',
60 get_keys => 'get_excluded_roles_list',
61 existence => 'excludes_role',
65 name => 'required_methods',
66 attr_reader => 'get_required_methods_map',
68 remove => 'remove_required_methods',
69 get_values => 'get_required_method_list',
70 existence => 'requires_method',
74 name => 'attribute_map',
75 attr_reader => 'get_attribute_map',
77 get => 'get_attribute',
78 get_keys => 'get_attribute_list',
79 existence => 'has_attribute',
80 remove => 'remove_attribute',
85 my $attr_reader = $action->{attr_reader};
86 my $methods = $action->{methods};
88 # create the attribute
89 $META->add_attribute($action->{name} => (
90 reader => $attr_reader,
94 # create some helper methods
95 $META->add_method($methods->{add} => sub {
96 my ($self, @values) = @_;
97 $self->$attr_reader->{$_} = undef foreach @values;
98 }) if exists $methods->{add};
100 $META->add_method($methods->{get_keys} => sub {
102 keys %{$self->$attr_reader};
103 }) if exists $methods->{get_keys};
105 $META->add_method($methods->{get_values} => sub {
107 values %{$self->$attr_reader};
108 }) if exists $methods->{get_values};
110 $META->add_method($methods->{get} => sub {
111 my ($self, $name) = @_;
112 $self->$attr_reader->{$name}
113 }) if exists $methods->{get};
115 $META->add_method($methods->{existence} => sub {
116 my ($self, $name) = @_;
117 exists $self->$attr_reader->{$name} ? 1 : 0;
118 }) if exists $methods->{existence};
120 $META->add_method($methods->{remove} => sub {
121 my ($self, @values) = @_;
122 delete $self->$attr_reader->{$_} foreach @values;
123 }) if exists $methods->{remove};
126 $META->add_attribute(
128 reader => 'method_metaclass',
129 default => 'Moose::Meta::Role::Method',
132 $META->add_attribute(
133 'required_method_metaclass',
134 reader => 'required_method_metaclass',
135 default => 'Moose::Meta::Role::Method::Required',
138 $META->add_attribute(
139 'conflicting_method_metaclass',
140 reader => 'conflicting_method_metaclass',
141 default => 'Moose::Meta::Role::Method::Conflicting',
144 $META->add_attribute(
145 'application_to_class_class',
146 reader => 'application_to_class_class',
147 default => 'Moose::Meta::Role::Application::ToClass',
150 $META->add_attribute(
151 'application_to_role_class',
152 reader => 'application_to_role_class',
153 default => 'Moose::Meta::Role::Application::ToRole',
156 $META->add_attribute(
157 'application_to_instance_class',
158 reader => 'application_to_instance_class',
159 default => 'Moose::Meta::Role::Application::ToInstance',
162 $META->add_attribute(
163 'composition_class_roles',
164 reader => 'composition_class_roles',
165 predicate => 'has_composition_class_roles',
168 ## some things don't always fit, so they go here ...
173 unless ( defined $name ) {
175 Moose->throw_error("You must provide a name for the attribute");
178 if (scalar @_ == 1 && ref($_[0]) eq 'HASH') {
184 $self->get_attribute_map->{$name} = $attr_desc;
187 sub add_required_methods {
192 if (!blessed($method)) {
193 $method = $self->required_method_metaclass->new(
197 $self->get_required_methods_map->{$method->name} = $method;
201 sub add_conflicting_method {
205 if (@_ == 1 && blessed($_[0])) {
209 $method = $self->conflicting_method_metaclass->new(@_);
212 $self->add_required_methods($method);
215 ## ------------------------------------------------------------------
219 # the before/around/after method modifiers are
220 # stored by name, but there can be many methods
221 # then associated with that name. So again we have
222 # lots of similar functionality, so we can do some
223 # meta-programmin' and save some time.
226 foreach my $modifier_type (qw[ before around after ]) {
228 my $attr_reader = "get_${modifier_type}_method_modifiers_map";
230 # create the attribute ...
231 $META->add_attribute("${modifier_type}_method_modifiers" => (
232 reader => $attr_reader,
233 default => sub { {} }
236 # and some helper methods ...
237 $META->add_method("get_${modifier_type}_method_modifiers" => sub {
238 my ($self, $method_name) = @_;
239 #return () unless exists $self->$attr_reader->{$method_name};
240 my $mm = $self->$attr_reader->{$method_name};
244 $META->add_method("has_${modifier_type}_method_modifiers" => sub {
245 my ($self, $method_name) = @_;
247 # for now we assume that if it exists,..
248 # it has at least one modifier in it
249 (exists $self->$attr_reader->{$method_name}) ? 1 : 0;
252 $META->add_method("add_${modifier_type}_method_modifier" => sub {
253 my ($self, $method_name, $method) = @_;
255 $self->$attr_reader->{$method_name} = []
256 unless exists $self->$attr_reader->{$method_name};
258 my $modifiers = $self->$attr_reader->{$method_name};
261 # check to see that we aren't adding the
262 # same code twice. We err in favor of the
263 # first on here, this may not be as expected
264 foreach my $modifier (@{$modifiers}) {
265 return if $modifier == $method;
268 push @{$modifiers} => $method;
273 ## ------------------------------------------------------------------
274 ## override method mofidiers
276 $META->add_attribute('override_method_modifiers' => (
277 reader => 'get_override_method_modifiers_map',
278 default => sub { {} }
282 # these are a little different because there
283 # can only be one per name, whereas the other
284 # method modifiers can have multiples.
287 sub add_override_method_modifier {
288 my ($self, $method_name, $method) = @_;
289 (!$self->has_method($method_name))
290 || Moose->throw_error("Cannot add an override of method '$method_name' " .
291 "because there is a local version of '$method_name'");
292 $self->get_override_method_modifiers_map->{$method_name} = $method;
295 sub has_override_method_modifier {
296 my ($self, $method_name) = @_;
298 # for now we assume that if it exists,..
299 # it has at least one modifier in it
300 (exists $self->get_override_method_modifiers_map->{$method_name}) ? 1 : 0;
303 sub get_override_method_modifier {
304 my ($self, $method_name) = @_;
305 $self->get_override_method_modifiers_map->{$method_name};
308 ## general list accessor ...
310 sub get_method_modifier_list {
311 my ($self, $modifier_type) = @_;
312 my $accessor = "get_${modifier_type}_method_modifiers_map";
313 keys %{$self->$accessor};
316 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
317 sub update_package_cache_flag {
319 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
324 ## ------------------------------------------------------------------
327 $META->add_attribute('roles' => (
328 reader => 'get_roles',
329 default => sub { [] }
333 my ($self, $role) = @_;
334 (blessed($role) && $role->isa('Moose::Meta::Role'))
335 || Moose->throw_error("Roles must be instances of Moose::Meta::Role");
336 push @{$self->get_roles} => $role;
337 $self->reset_package_cache_flag;
340 sub calculate_all_roles {
346 $_->calculate_all_roles
347 } @{ $self->get_roles });
351 my ($self, $role_name) = @_;
353 || Moose->throw_error("You must supply a role name to look for");
354 # if we are it,.. then return true
355 return 1 if $role_name eq $self->name;
356 # otherwise.. check our children
357 foreach my $role (@{$self->get_roles}) {
358 return 1 if $role->does_role($role_name);
363 sub find_method_by_name { (shift)->get_method(@_) }
366 Carp::cluck("The alias_method method is deprecated. Use add_method instead.\n");
370 $self->add_method(@_);
373 ## ------------------------------------------------------------------
375 ## ------------------------------------------------------------------
378 my ($self, $other, @args) = @_;
381 || Moose->throw_error("You must pass in an blessed instance");
383 my $application_class;
384 if ($other->isa('Moose::Meta::Role')) {
385 $application_class = $self->application_to_role_class;
387 elsif ($other->isa('Moose::Meta::Class')) {
388 $application_class = $self->application_to_class_class;
391 $application_class = $self->application_to_instance_class;
394 Class::MOP::load_class($application_class);
395 return $application_class->new(@args)->apply($self, $other);
399 my ($class, @role_specs) = @_;
401 require Moose::Meta::Role::Composite;
403 my (@roles, %role_params);
404 while (@role_specs) {
405 my ($role_name, $params) = @{ splice @role_specs, 0, 1 };
406 my $requested_role = Class::MOP::class_of($role_name);
408 my $actual_role = $requested_role->_role_for_combination($params);
409 push @roles => $actual_role;
411 next unless defined $params;
412 $role_params{$actual_role->name} = $params;
415 my $c = Moose::Meta::Role::Composite->new(roles => \@roles);
416 return $c->apply_params(\%role_params);
419 sub _role_for_combination {
420 my ($self, $params) = @_;
425 my ( $role, $package_name, %options ) = @_;
427 $options{package} = $package_name;
429 (ref $options{attributes} eq 'HASH')
430 || confess "You must pass a HASH ref of attributes"
431 if exists $options{attributes};
433 (ref $options{methods} eq 'HASH')
434 || confess "You must pass a HASH ref of methods"
435 if exists $options{methods};
437 my (%initialize_options) = %options;
438 delete @initialize_options{qw(
446 my $meta = $role->initialize( $package_name => %initialize_options );
448 $meta->_instantiate_module( $options{version}, $options{authority} );
451 $meta->add_method('meta' => sub {
452 $role->initialize(ref($_[0]) || $_[0]);
455 if (exists $options{attributes}) {
456 foreach my $attribute_name (keys %{$options{attributes}}) {
457 my $attr = $options{attributes}->{$attribute_name};
458 $meta->add_attribute($attribute_name => $attr);
462 if (exists $options{methods}) {
463 foreach my $method_name (keys %{$options{methods}}) {
464 $meta->add_method($method_name, $options{methods}->{$method_name});
468 Class::MOP::weaken_metaclass($meta->name)
469 if $meta->is_anon_role;
474 # anonymous roles. most of it is copied straight out of Class::MOP::Class.
475 # an intrepid hacker might find great riches if he unifies this code with that
476 # code in Class::MOP::Module or Class::MOP::Package
479 # this should be sufficient, if you have a
480 # use case where it is not, write a test and
482 my $ANON_ROLE_SERIAL = 0;
485 # we need a sufficiently annoying prefix
486 # this should suffice for now, this is
487 # used in a couple of places below, so
488 # need to put it up here for now.
489 my $ANON_ROLE_PREFIX = 'Moose::Meta::Role::__ANON__::SERIAL::';
493 no warnings 'uninitialized';
494 $self->name =~ /^$ANON_ROLE_PREFIX/;
497 sub create_anon_role {
498 my ($role, %options) = @_;
499 my $package_name = $ANON_ROLE_PREFIX . ++$ANON_ROLE_SERIAL;
500 return $role->create($package_name, %options);
504 # this will only get called for
505 # anon-roles, all other calls
506 # are assumed to occur during
507 # global destruction and so don't
508 # really need to be handled explicitly
512 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
514 no warnings 'uninitialized';
515 return unless $self->name =~ /^$ANON_ROLE_PREFIX/;
517 # XXX: is this necessary for us? I don't understand what it's doing
520 # Moose does a weird thing where it replaces the metaclass for
521 # class when fixing metaclass incompatibility. In that case,
522 # we don't want to clean out the namespace now. We can detect
523 # that because Moose will explicitly update the singleton
524 # cache in Class::MOP.
525 #my $current_meta = Class::MOP::get_metaclass_by_name($self->name);
526 #return if $current_meta ne $self;
528 my ($serial_id) = ($self->name =~ /^$ANON_ROLE_PREFIX(\d+)/);
530 foreach my $key (keys %{$ANON_ROLE_PREFIX . $serial_id}) {
531 delete ${$ANON_ROLE_PREFIX . $serial_id}{$key};
533 delete ${'main::' . $ANON_ROLE_PREFIX}{$serial_id . '::'};
537 #####################################################################
539 ## This is Moose::Meta::Role as defined by Moose (plus the use of
540 ## MooseX::AttributeHelpers module). It is here as a reference to
541 ## make it easier to see what is happening above with all the meta
543 #####################################################################
546 # metaclass => 'Array',
547 # reader => 'get_roles',
548 # isa => 'ArrayRef[Moose::Meta::Role]',
549 # default => sub { [] },
551 # 'push' => 'add_role',
555 # has 'excluded_roles_map' => (
556 # metaclass => 'Hash',
557 # reader => 'get_excluded_roles_map',
558 # isa => 'HashRef[Str]',
560 # # Not exactly set, cause it sets multiple
561 # 'set' => 'add_excluded_roles',
562 # 'keys' => 'get_excluded_roles_list',
563 # 'exists' => 'excludes_role',
567 # has 'attribute_map' => (
568 # metaclass => 'Hash',
569 # reader => 'get_attribute_map',
570 # isa => 'HashRef[Str]',
572 # # 'set' => 'add_attribute' # has some special crap in it
573 # 'get' => 'get_attribute',
574 # 'keys' => 'get_attribute_list',
575 # 'exists' => 'has_attribute',
576 # # Not exactly delete, cause it sets multiple
577 # 'delete' => 'remove_attribute',
581 # has 'required_methods' => (
582 # metaclass => 'Hash',
583 # reader => 'get_required_methods_map',
584 # isa => 'HashRef[Moose::Meta::Role::Method::Required]',
586 # # not exactly set, or delete since it works for multiple
587 # 'set' => 'add_required_methods',
588 # 'delete' => 'remove_required_methods',
589 # 'keys' => 'get_required_method_list',
590 # 'exists' => 'requires_method',
594 # # the before, around and after modifiers are
595 # # HASH keyed by method-name, with ARRAY of
596 # # CODE refs to apply in that order
598 # has 'before_method_modifiers' => (
599 # metaclass => 'Hash',
600 # reader => 'get_before_method_modifiers_map',
601 # isa => 'HashRef[ArrayRef[CodeRef]]',
603 # 'keys' => 'get_before_method_modifiers',
604 # 'exists' => 'has_before_method_modifiers',
605 # # This actually makes sure there is an
606 # # ARRAY at the given key, and pushed onto
607 # # it. It also checks for duplicates as well
608 # # 'add' => 'add_before_method_modifier'
612 # has 'after_method_modifiers' => (
613 # metaclass => 'Hash',
614 # reader =>'get_after_method_modifiers_map',
615 # isa => 'HashRef[ArrayRef[CodeRef]]',
617 # 'keys' => 'get_after_method_modifiers',
618 # 'exists' => 'has_after_method_modifiers',
619 # # This actually makes sure there is an
620 # # ARRAY at the given key, and pushed onto
621 # # it. It also checks for duplicates as well
622 # # 'add' => 'add_after_method_modifier'
626 # has 'around_method_modifiers' => (
627 # metaclass => 'Hash',
628 # reader =>'get_around_method_modifiers_map',
629 # isa => 'HashRef[ArrayRef[CodeRef]]',
631 # 'keys' => 'get_around_method_modifiers',
632 # 'exists' => 'has_around_method_modifiers',
633 # # This actually makes sure there is an
634 # # ARRAY at the given key, and pushed onto
635 # # it. It also checks for duplicates as well
636 # # 'add' => 'add_around_method_modifier'
640 # # override is similar to the other modifiers
641 # # except that it is not an ARRAY of code refs
642 # # but instead just a single name->code mapping
644 # has 'override_method_modifiers' => (
645 # metaclass => 'Hash',
646 # reader =>'get_override_method_modifiers_map',
647 # isa => 'HashRef[CodeRef]',
649 # 'keys' => 'get_override_method_modifier',
650 # 'exists' => 'has_override_method_modifier',
651 # 'add' => 'add_override_method_modifier', # checks for local method ..
655 #####################################################################
666 Moose::Meta::Role - The Moose Role metaclass
670 This class is a subclass of L<Class::MOP::Module> that provides
671 additional Moose-specific functionality.
673 It's API looks a lot like L<Moose::Meta::Class>, but internally it
674 implements many things differently. This may change in the future.
678 C<Moose::Meta::Role> is a subclass of L<Class::MOP::Module>.
686 =item B<< Moose::Meta::Role->initialize($role_name) >>
688 This method creates a new role object with the provided name.
690 =item B<< Moose::Meta::Role->combine( [ $role => { ... } ], [ $role ], ... ) >>
692 This method accepts a list of array references. Each array reference
693 should contain a role name as its first element. The second element is
694 an optional hash reference. The hash reference can contain C<-excludes>
695 and C<-alias> keys to control how methods are composed from the role.
697 The return value is a new L<Moose::Meta::Role::Composite> that
698 represents the combined roles.
700 =item B<< Moose::Meta::Role->create($name, %options) >>
702 This method is identical to the L<Moose::Meta::Class> C<create>
705 =item B<< Moose::Meta::Role->create_anon_role >>
707 This method is identical to the L<Moose::Meta::Class>
708 C<create_anon_class> method.
710 =item B<< $metarole->is_anon_role >>
712 Returns true if the role is an anonymous role.
716 =head2 Role application
720 =item B<< $metarole->apply( $thing, @options ) >>
722 This method applies a role to the given C<$thing>. That can be another
723 L<Moose::Meta::Role>, object, a L<Moose::Meta::Class> object, or a
724 (non-meta) object instance.
726 The options are passed directly to the constructor for the appropriate
727 L<Moose::Meta::Role::Application> subclass.
729 Note that this will apply the role even if the C<$thing> in question already
730 C<does> this role. L<Moose::Util/does_role> is a convenient wrapper for
731 finding out if role application is necessary.
735 =head2 Roles and other roles
739 =item B<< $metarole->get_roles >>
741 This returns an array reference of roles which this role does. This
742 list may include duplicates.
744 =item B<< $metarole->calculate_all_roles >>
746 This returns a I<unique> list of all roles that this role does, and
747 all the roles that its roles do.
749 =item B<< $metarole->does_role($role_name) >>
751 Given a role I<name>, returns true if this role does the given
754 =item B<< $metarole->add_role($role) >>
756 Given a L<Moose::Meta::Role> object, this adds the role to the list of
757 roles that the role does.
759 =item B<< $metarole->get_excluded_roles_list >>
761 Returns a list of role names which this role excludes.
763 =item B<< $metarole->excludes_role($role_name) >>
765 Given a role I<name>, returns true if this role excludes the named
768 =item B<< $metarole->add_excluded_roles(@role_names) >>
770 Given one or more role names, adds those roles to the list of excluded
777 The methods for dealing with a role's methods are all identical in API
778 and behavior to the same methods in L<Class::MOP::Class>.
782 =item B<< $metarole->method_metaclass >>
784 Returns the method metaclass name for the role. This defaults to
785 L<Moose::Meta::Role::Method>.
787 =item B<< $metarole->get_method($name) >>
789 =item B<< $metarole->has_method($name) >>
791 =item B<< $metarole->add_method( $name, $body ) >>
793 =item B<< $metarole->get_method_list >>
795 =item B<< $metarole->find_method_by_name($name) >>
797 These methods are all identical to the methods of the same name in
798 L<Class::MOP::Package>
804 As with methods, the methods for dealing with a role's attribute are
805 all identical in API and behavior to the same methods in
806 L<Class::MOP::Class>.
808 However, attributes stored in this class are I<not> stored as
809 objects. Rather, the attribute definition is stored as a hash
810 reference. When a role is composed into a class, this hash reference
811 is passed directly to the metaclass's C<add_attribute> method.
813 This is quite likely to change in the future.
817 =item B<< $metarole->get_attribute($attribute_name) >>
819 =item B<< $metarole->has_attribute($attribute_name) >>
821 =item B<< $metarole->get_attribute_map >>
823 =item B<< $metarole->get_attribute_list >>
825 =item B<< $metarole->add_attribute($name, %options) >>
827 =item B<< $metarole->remove_attribute($attribute_name) >>
831 =head2 Required methods
835 =item B<< $metarole->get_required_method_list >>
837 Returns the list of methods required by the role.
839 =item B<< $metarole->requires_method($name) >>
841 Returns true if the role requires the named method.
843 =item B<< $metarole->add_required_methods(@names) >>
845 Adds the named methods to the role's list of required methods.
847 =item B<< $metarole->remove_required_methods(@names) >>
849 Removes the named methods from the role's list of required methods.
851 =item B<< $metarole->add_conflicting_method(%params) >>
853 Instantiate the parameters as a L<Moose::Meta::Role::Method::Conflicting>
854 object, then add it to the required method list.
858 =head2 Method modifiers
860 These methods act like their counterparts in L<Class::Mop::Class> and
861 L<Moose::Meta::Class>.
863 However, method modifiers are simply stored internally, and are not
864 applied until the role itself is applied to a class.
868 =item B<< $metarole->add_after_method_modifier($method_name, $method) >>
870 =item B<< $metarole->add_around_method_modifier($method_name, $method) >>
872 =item B<< $metarole->add_before_method_modifier($method_name, $method) >>
874 =item B<< $metarole->add_override_method_modifier($method_name, $method) >>
876 These methods all add an appropriate modifier to the internal list of
879 =item B<< $metarole->has_after_method_modifiers >>
881 =item B<< $metarole->has_around_method_modifiers >>
883 =item B<< $metarole->has_before_method_modifiers >>
885 =item B<< $metarole->has_override_method_modifier >>
887 Return true if the role has any modifiers of the given type.
889 =item B<< $metarole->get_after_method_modifiers($method_name) >>
891 =item B<< $metarole->get_around_method_modifiers($method_name) >>
893 =item B<< $metarole->get_before_method_modifiers($method_name) >>
895 Given a method name, returns a list of the appropriate modifiers for
898 =item B<< $metarole->get_override_method_modifier($method_name) >>
900 Given a method name, returns the override method modifier for that
901 method, if it has one.
909 =item B<< Moose::Meta::Role->meta >>
911 This will return a L<Class::MOP::Class> instance for this class.
917 All complex software has bugs lurking in it, and this module is no
918 exception. If you find a bug please either email me, or add the bug
923 Stevan Little E<lt>stevan@iinteractive.comE<gt>
925 =head1 COPYRIGHT AND LICENSE
927 Copyright 2006-2009 by Infinity Interactive, Inc.
929 L<http://www.iinteractive.com>
931 This library is free software; you can redistribute it and/or modify
932 it under the same terms as Perl itself.