2 package Moose::Meta::Role;
8 use Scalar::Util 'blessed';
10 use Devel::GlobalDestruction 'in_global_destruction';
12 our $VERSION = '0.93';
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 => '_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 ## some things don't always fit, so they go here ...
167 unless ( defined $name ) {
169 Moose->throw_error("You must provide a name for the attribute");
172 if (scalar @_ == 1 && ref($_[0]) eq 'HASH') {
178 $self->_attribute_map->{$name} = $attr_desc;
181 sub add_required_methods {
186 if (!blessed($method)) {
187 $method = $self->required_method_metaclass->new(
191 $self->get_required_methods_map->{$method->name} = $method;
195 sub add_conflicting_method {
199 if (@_ == 1 && blessed($_[0])) {
203 $method = $self->conflicting_method_metaclass->new(@_);
206 $self->add_required_methods($method);
209 ## ------------------------------------------------------------------
213 # the before/around/after method modifiers are
214 # stored by name, but there can be many methods
215 # then associated with that name. So again we have
216 # lots of similar functionality, so we can do some
217 # meta-programmin' and save some time.
220 foreach my $modifier_type (qw[ before around after ]) {
222 my $attr_reader = "get_${modifier_type}_method_modifiers_map";
224 # create the attribute ...
225 $META->add_attribute("${modifier_type}_method_modifiers" => (
226 reader => $attr_reader,
227 default => sub { {} }
230 # and some helper methods ...
231 $META->add_method("get_${modifier_type}_method_modifiers" => sub {
232 my ($self, $method_name) = @_;
233 #return () unless exists $self->$attr_reader->{$method_name};
234 my $mm = $self->$attr_reader->{$method_name};
238 $META->add_method("has_${modifier_type}_method_modifiers" => sub {
239 my ($self, $method_name) = @_;
241 # for now we assume that if it exists,..
242 # it has at least one modifier in it
243 (exists $self->$attr_reader->{$method_name}) ? 1 : 0;
246 $META->add_method("add_${modifier_type}_method_modifier" => sub {
247 my ($self, $method_name, $method) = @_;
249 $self->$attr_reader->{$method_name} = []
250 unless exists $self->$attr_reader->{$method_name};
252 my $modifiers = $self->$attr_reader->{$method_name};
255 # check to see that we aren't adding the
256 # same code twice. We err in favor of the
257 # first on here, this may not be as expected
258 foreach my $modifier (@{$modifiers}) {
259 return if $modifier == $method;
262 push @{$modifiers} => $method;
267 ## ------------------------------------------------------------------
268 ## override method mofidiers
270 $META->add_attribute('override_method_modifiers' => (
271 reader => 'get_override_method_modifiers_map',
272 default => sub { {} }
276 # these are a little different because there
277 # can only be one per name, whereas the other
278 # method modifiers can have multiples.
281 sub add_override_method_modifier {
282 my ($self, $method_name, $method) = @_;
283 (!$self->has_method($method_name))
284 || Moose->throw_error("Cannot add an override of method '$method_name' " .
285 "because there is a local version of '$method_name'");
286 $self->get_override_method_modifiers_map->{$method_name} = $method;
289 sub has_override_method_modifier {
290 my ($self, $method_name) = @_;
292 # for now we assume that if it exists,..
293 # it has at least one modifier in it
294 (exists $self->get_override_method_modifiers_map->{$method_name}) ? 1 : 0;
297 sub get_override_method_modifier {
298 my ($self, $method_name) = @_;
299 $self->get_override_method_modifiers_map->{$method_name};
302 ## general list accessor ...
304 sub get_method_modifier_list {
305 my ($self, $modifier_type) = @_;
306 my $accessor = "get_${modifier_type}_method_modifiers_map";
307 keys %{$self->$accessor};
310 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
311 sub update_package_cache_flag {
313 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
318 ## ------------------------------------------------------------------
321 $META->add_attribute('roles' => (
322 reader => 'get_roles',
323 default => sub { [] }
327 my ($self, $role) = @_;
328 (blessed($role) && $role->isa('Moose::Meta::Role'))
329 || Moose->throw_error("Roles must be instances of Moose::Meta::Role");
330 push @{$self->get_roles} => $role;
331 $self->reset_package_cache_flag;
334 sub calculate_all_roles {
340 $_->calculate_all_roles
341 } @{ $self->get_roles });
345 my ($self, $role_name) = @_;
347 || Moose->throw_error("You must supply a role name to look for");
348 # if we are it,.. then return true
349 return 1 if $role_name eq $self->name;
350 # otherwise.. check our children
351 foreach my $role (@{$self->get_roles}) {
352 return 1 if $role->does_role($role_name);
357 sub find_method_by_name { (shift)->get_method(@_) }
360 Carp::cluck("The alias_method method is deprecated. Use add_method instead.\n");
364 $self->add_method(@_);
367 ## ------------------------------------------------------------------
369 ## ------------------------------------------------------------------
372 my ($self, $other, @args) = @_;
375 || Moose->throw_error("You must pass in an blessed instance");
377 my $application_class;
378 if ($other->isa('Moose::Meta::Role')) {
379 $application_class = $self->application_to_role_class;
381 elsif ($other->isa('Moose::Meta::Class')) {
382 $application_class = $self->application_to_class_class;
385 $application_class = $self->application_to_instance_class;
388 Class::MOP::load_class($application_class);
389 return $application_class->new(@args)->apply($self, $other);
392 sub composition_class_roles { }
395 my ($class, @role_specs) = @_;
397 require Moose::Meta::Role::Composite;
399 my (@roles, %role_params);
400 while (@role_specs) {
401 my ($role_name, $params) = @{ splice @role_specs, 0, 1 };
402 my $requested_role = Class::MOP::class_of($role_name);
404 my $actual_role = $requested_role->_role_for_combination($params);
405 push @roles => $actual_role;
407 next unless defined $params;
408 $role_params{$actual_role->name} = $params;
411 my $c = Moose::Meta::Role::Composite->new(roles => \@roles);
412 return $c->apply_params(\%role_params);
415 sub _role_for_combination {
416 my ($self, $params) = @_;
421 my ( $role, $package_name, %options ) = @_;
423 $options{package} = $package_name;
425 (ref $options{attributes} eq 'HASH')
426 || confess "You must pass a HASH ref of attributes"
427 if exists $options{attributes};
429 (ref $options{methods} eq 'HASH')
430 || confess "You must pass a HASH ref of methods"
431 if exists $options{methods};
433 my (%initialize_options) = %options;
434 delete @initialize_options{qw(
442 my $meta = $role->initialize( $package_name => %initialize_options );
444 $meta->_instantiate_module( $options{version}, $options{authority} );
447 $meta->add_method('meta' => sub {
448 $role->initialize(ref($_[0]) || $_[0]);
451 if (exists $options{attributes}) {
452 foreach my $attribute_name (keys %{$options{attributes}}) {
453 my $attr = $options{attributes}->{$attribute_name};
454 $meta->add_attribute($attribute_name => $attr);
458 if (exists $options{methods}) {
459 foreach my $method_name (keys %{$options{methods}}) {
460 $meta->add_method($method_name, $options{methods}->{$method_name});
464 Class::MOP::weaken_metaclass($meta->name)
465 if $meta->is_anon_role;
470 # anonymous roles. most of it is copied straight out of Class::MOP::Class.
471 # an intrepid hacker might find great riches if he unifies this code with that
472 # code in Class::MOP::Module or Class::MOP::Package
475 # this should be sufficient, if you have a
476 # use case where it is not, write a test and
478 my $ANON_ROLE_SERIAL = 0;
481 # we need a sufficiently annoying prefix
482 # this should suffice for now, this is
483 # used in a couple of places below, so
484 # need to put it up here for now.
485 my $ANON_ROLE_PREFIX = 'Moose::Meta::Role::__ANON__::SERIAL::';
489 no warnings 'uninitialized';
490 $self->name =~ /^$ANON_ROLE_PREFIX/;
493 sub create_anon_role {
494 my ($role, %options) = @_;
495 my $package_name = $ANON_ROLE_PREFIX . ++$ANON_ROLE_SERIAL;
496 return $role->create($package_name, %options);
500 # this will only get called for
501 # anon-roles, all other calls
502 # are assumed to occur during
503 # global destruction and so don't
504 # really need to be handled explicitly
508 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
510 no warnings 'uninitialized';
511 return unless $self->name =~ /^$ANON_ROLE_PREFIX/;
513 # XXX: is this necessary for us? I don't understand what it's doing
516 # Moose does a weird thing where it replaces the metaclass for
517 # class when fixing metaclass incompatibility. In that case,
518 # we don't want to clean out the namespace now. We can detect
519 # that because Moose will explicitly update the singleton
520 # cache in Class::MOP.
521 #my $current_meta = Class::MOP::get_metaclass_by_name($self->name);
522 #return if $current_meta ne $self;
524 my ($serial_id) = ($self->name =~ /^$ANON_ROLE_PREFIX(\d+)/);
526 foreach my $key (keys %{$ANON_ROLE_PREFIX . $serial_id}) {
527 delete ${$ANON_ROLE_PREFIX . $serial_id}{$key};
529 delete ${'main::' . $ANON_ROLE_PREFIX}{$serial_id . '::'};
533 #####################################################################
535 ## This is Moose::Meta::Role as defined by Moose (plus the use of
536 ## MooseX::AttributeHelpers module). It is here as a reference to
537 ## make it easier to see what is happening above with all the meta
539 #####################################################################
542 # metaclass => 'Array',
543 # reader => 'get_roles',
544 # isa => 'ArrayRef[Moose::Meta::Role]',
545 # default => sub { [] },
547 # 'push' => 'add_role',
551 # has 'excluded_roles_map' => (
552 # metaclass => 'Hash',
553 # reader => 'get_excluded_roles_map',
554 # isa => 'HashRef[Str]',
556 # # Not exactly set, cause it sets multiple
557 # 'set' => 'add_excluded_roles',
558 # 'keys' => 'get_excluded_roles_list',
559 # 'exists' => 'excludes_role',
563 # has 'attribute_map' => (
564 # metaclass => 'Hash',
565 # reader => '_attribute_map',
566 # isa => 'HashRef[Str]',
568 # # 'set' => 'add_attribute' # has some special crap in it
569 # 'get' => 'get_attribute',
570 # 'keys' => 'get_attribute_list',
571 # 'exists' => 'has_attribute',
572 # # Not exactly delete, cause it sets multiple
573 # 'delete' => 'remove_attribute',
577 # has 'required_methods' => (
578 # metaclass => 'Hash',
579 # reader => 'get_required_methods_map',
580 # isa => 'HashRef[Moose::Meta::Role::Method::Required]',
582 # # not exactly set, or delete since it works for multiple
583 # 'set' => 'add_required_methods',
584 # 'delete' => 'remove_required_methods',
585 # 'keys' => 'get_required_method_list',
586 # 'exists' => 'requires_method',
590 # # the before, around and after modifiers are
591 # # HASH keyed by method-name, with ARRAY of
592 # # CODE refs to apply in that order
594 # has 'before_method_modifiers' => (
595 # metaclass => 'Hash',
596 # reader => 'get_before_method_modifiers_map',
597 # isa => 'HashRef[ArrayRef[CodeRef]]',
599 # 'keys' => 'get_before_method_modifiers',
600 # 'exists' => 'has_before_method_modifiers',
601 # # This actually makes sure there is an
602 # # ARRAY at the given key, and pushed onto
603 # # it. It also checks for duplicates as well
604 # # 'add' => 'add_before_method_modifier'
608 # has 'after_method_modifiers' => (
609 # metaclass => 'Hash',
610 # reader =>'get_after_method_modifiers_map',
611 # isa => 'HashRef[ArrayRef[CodeRef]]',
613 # 'keys' => 'get_after_method_modifiers',
614 # 'exists' => 'has_after_method_modifiers',
615 # # This actually makes sure there is an
616 # # ARRAY at the given key, and pushed onto
617 # # it. It also checks for duplicates as well
618 # # 'add' => 'add_after_method_modifier'
622 # has 'around_method_modifiers' => (
623 # metaclass => 'Hash',
624 # reader =>'get_around_method_modifiers_map',
625 # isa => 'HashRef[ArrayRef[CodeRef]]',
627 # 'keys' => 'get_around_method_modifiers',
628 # 'exists' => 'has_around_method_modifiers',
629 # # This actually makes sure there is an
630 # # ARRAY at the given key, and pushed onto
631 # # it. It also checks for duplicates as well
632 # # 'add' => 'add_around_method_modifier'
636 # # override is similar to the other modifiers
637 # # except that it is not an ARRAY of code refs
638 # # but instead just a single name->code mapping
640 # has 'override_method_modifiers' => (
641 # metaclass => 'Hash',
642 # reader =>'get_override_method_modifiers_map',
643 # isa => 'HashRef[CodeRef]',
645 # 'keys' => 'get_override_method_modifier',
646 # 'exists' => 'has_override_method_modifier',
647 # 'add' => 'add_override_method_modifier', # checks for local method ..
651 #####################################################################
662 Moose::Meta::Role - The Moose Role metaclass
666 This class is a subclass of L<Class::MOP::Module> that provides
667 additional Moose-specific functionality.
669 It's API looks a lot like L<Moose::Meta::Class>, but internally it
670 implements many things differently. This may change in the future.
674 C<Moose::Meta::Role> is a subclass of L<Class::MOP::Module>.
682 =item B<< Moose::Meta::Role->initialize($role_name) >>
684 This method creates a new role object with the provided name.
686 =item B<< Moose::Meta::Role->combine( [ $role => { ... } ], [ $role ], ... ) >>
688 This method accepts a list of array references. Each array reference
689 should contain a role name as its first element. The second element is
690 an optional hash reference. The hash reference can contain C<-excludes>
691 and C<-alias> keys to control how methods are composed from the role.
693 The return value is a new L<Moose::Meta::Role::Composite> that
694 represents the combined roles.
696 =item B<< $metarole->composition_class_roles >>
698 When combining multiple roles using C<combine>, this method is used to obtain a
699 list of role names to be applied to the L<Moose::Meta::Role::Composite>
700 instance returned by C<combine>. The default implementation returns an empty
701 list. Extensions that need to hook into role combination may wrap this method
702 to return additional role names.
704 =item B<< Moose::Meta::Role->create($name, %options) >>
706 This method is identical to the L<Moose::Meta::Class> C<create>
709 =item B<< Moose::Meta::Role->create_anon_role >>
711 This method is identical to the L<Moose::Meta::Class>
712 C<create_anon_class> method.
714 =item B<< $metarole->is_anon_role >>
716 Returns true if the role is an anonymous role.
720 =head2 Role application
724 =item B<< $metarole->apply( $thing, @options ) >>
726 This method applies a role to the given C<$thing>. That can be another
727 L<Moose::Meta::Role>, object, a L<Moose::Meta::Class> object, or a
728 (non-meta) object instance.
730 The options are passed directly to the constructor for the appropriate
731 L<Moose::Meta::Role::Application> subclass.
733 Note that this will apply the role even if the C<$thing> in question already
734 C<does> this role. L<Moose::Util/does_role> is a convenient wrapper for
735 finding out if role application is necessary.
739 =head2 Roles and other roles
743 =item B<< $metarole->get_roles >>
745 This returns an array reference of roles which this role does. This
746 list may include duplicates.
748 =item B<< $metarole->calculate_all_roles >>
750 This returns a I<unique> list of all roles that this role does, and
751 all the roles that its roles do.
753 =item B<< $metarole->does_role($role_name) >>
755 Given a role I<name>, returns true if this role does the given
758 =item B<< $metarole->add_role($role) >>
760 Given a L<Moose::Meta::Role> object, this adds the role to the list of
761 roles that the role does.
763 =item B<< $metarole->get_excluded_roles_list >>
765 Returns a list of role names which this role excludes.
767 =item B<< $metarole->excludes_role($role_name) >>
769 Given a role I<name>, returns true if this role excludes the named
772 =item B<< $metarole->add_excluded_roles(@role_names) >>
774 Given one or more role names, adds those roles to the list of excluded
781 The methods for dealing with a role's methods are all identical in API
782 and behavior to the same methods in L<Class::MOP::Class>.
786 =item B<< $metarole->method_metaclass >>
788 Returns the method metaclass name for the role. This defaults to
789 L<Moose::Meta::Role::Method>.
791 =item B<< $metarole->get_method($name) >>
793 =item B<< $metarole->has_method($name) >>
795 =item B<< $metarole->add_method( $name, $body ) >>
797 =item B<< $metarole->get_method_list >>
799 =item B<< $metarole->find_method_by_name($name) >>
801 These methods are all identical to the methods of the same name in
802 L<Class::MOP::Package>
808 As with methods, the methods for dealing with a role's attribute are
809 all identical in API and behavior to the same methods in
810 L<Class::MOP::Class>.
812 However, attributes stored in this class are I<not> stored as
813 objects. Rather, the attribute definition is stored as a hash
814 reference. When a role is composed into a class, this hash reference
815 is passed directly to the metaclass's C<add_attribute> method.
817 This is quite likely to change in the future.
821 =item B<< $metarole->get_attribute($attribute_name) >>
823 =item B<< $metarole->has_attribute($attribute_name) >>
825 =item B<< $metarole->get_attribute_list >>
827 =item B<< $metarole->add_attribute($name, %options) >>
829 =item B<< $metarole->remove_attribute($attribute_name) >>
833 =head2 Required methods
837 =item B<< $metarole->get_required_method_list >>
839 Returns the list of methods required by the role.
841 =item B<< $metarole->requires_method($name) >>
843 Returns true if the role requires the named method.
845 =item B<< $metarole->add_required_methods(@names) >>
847 Adds the named methods to the role's list of required methods.
849 =item B<< $metarole->remove_required_methods(@names) >>
851 Removes the named methods from the role's list of required methods.
853 =item B<< $metarole->add_conflicting_method(%params) >>
855 Instantiate the parameters as a L<Moose::Meta::Role::Method::Conflicting>
856 object, then add it to the required method list.
860 =head2 Method modifiers
862 These methods act like their counterparts in L<Class::Mop::Class> and
863 L<Moose::Meta::Class>.
865 However, method modifiers are simply stored internally, and are not
866 applied until the role itself is applied to a class.
870 =item B<< $metarole->add_after_method_modifier($method_name, $method) >>
872 =item B<< $metarole->add_around_method_modifier($method_name, $method) >>
874 =item B<< $metarole->add_before_method_modifier($method_name, $method) >>
876 =item B<< $metarole->add_override_method_modifier($method_name, $method) >>
878 These methods all add an appropriate modifier to the internal list of
881 =item B<< $metarole->has_after_method_modifiers >>
883 =item B<< $metarole->has_around_method_modifiers >>
885 =item B<< $metarole->has_before_method_modifiers >>
887 =item B<< $metarole->has_override_method_modifier >>
889 Return true if the role has any modifiers of the given type.
891 =item B<< $metarole->get_after_method_modifiers($method_name) >>
893 =item B<< $metarole->get_around_method_modifiers($method_name) >>
895 =item B<< $metarole->get_before_method_modifiers($method_name) >>
897 Given a method name, returns a list of the appropriate modifiers for
900 =item B<< $metarole->get_override_method_modifier($method_name) >>
902 Given a method name, returns the override method modifier for that
903 method, if it has one.
911 =item B<< Moose::Meta::Role->meta >>
913 This will return a L<Class::MOP::Class> instance for this class.
919 All complex software has bugs lurking in it, and this module is no
920 exception. If you find a bug please either email me, or add the bug
925 Stevan Little E<lt>stevan@iinteractive.comE<gt>
927 =head1 COPYRIGHT AND LICENSE
929 Copyright 2006-2009 by Infinity Interactive, Inc.
931 L<http://www.iinteractive.com>
933 This library is free software; you can redistribute it and/or modify
934 it under the same terms as Perl itself.