support requires on Mouse::Role.
[gitmo/Mouse.git] / lib / Mouse / Meta / Role.pm
CommitLineData
a2227e71 1#!/usr/bin/env perl
2package Mouse::Meta::Role;
3use strict;
4use warnings;
59089ec3 5use Carp 'confess';
a2227e71 6
acf0f643 7do {
8 my %METACLASS_CACHE;
9
10 # because Mouse doesn't introspect existing classes, we're forced to
11 # only pay attention to other Mouse classes
12 sub _metaclass_cache {
13 my $class = shift;
14 my $name = shift;
15 return $METACLASS_CACHE{$name};
16 }
17
18 sub initialize {
19 my $class = shift;
20 my $name = shift;
21 $METACLASS_CACHE{$name} = $class->new(name => $name)
22 if !exists($METACLASS_CACHE{$name});
23 return $METACLASS_CACHE{$name};
24 }
25};
26
27sub new {
28 my $class = shift;
29 my %args = @_;
30
59089ec3 31 $args{attributes} ||= {};
32 $args{required_methods} ||= [];
274b6cce 33
acf0f643 34 bless \%args, $class;
35}
a2227e71 36
513854c7 37sub name { $_[0]->{name} }
38
59089ec3 39sub add_required_methods {
40 my $self = shift;
41 my @methods = @_;
42 push @{$self->{required_methods}}, @methods;
43}
44
274b6cce 45sub add_attribute {
46 my $self = shift;
47 my $name = shift;
69ac1dcf 48 my $spec = shift;
49 $self->{attributes}->{$name} = $spec;
da0c885d 50}
51
274b6cce 52sub has_attribute { exists $_[0]->{attributes}->{$_[1]} }
53sub get_attribute_list { keys %{ $_[0]->{attributes} } }
69ac1dcf 54sub get_attribute { $_[0]->{attributes}->{$_[1]} }
274b6cce 55
da0c885d 56sub apply {
57 my $self = shift;
58 my $class = shift;
da0c885d 59
59089ec3 60 for my $name (@{$self->{required_methods}}) {
61 unless ($class->name->can($name)) {
62 confess "'@{[ $self->name ]}' requires the method '$name' to be implemented by '@{[ $class->name ]}'";
63 }
64 }
65
da0c885d 66 for my $name ($self->get_attribute_list) {
0ba3591e 67 next if $class->has_attribute($name);
ba33632e 68 my $spec = $self->get_attribute($name);
724c77c0 69 Mouse::Meta::Attribute->create($class, $name, %$spec);
da0c885d 70 }
d99db7b6 71
72 for my $modifier_type (qw/before after around/) {
73 my $add_method = "add_${modifier_type}_method_modifier";
74 my $modified = $self->{"${modifier_type}_method_modifiers"};
75
76 for my $method_name (keys %$modified) {
77 for my $code (@{ $modified->{$method_name} }) {
78 $class->$add_method($method_name => $code);
79 }
80 }
81 }
da0c885d 82}
0fc8adbc 83
c2f128e7 84for my $modifier_type (qw/before after around/) {
85 no strict 'refs';
fc0e0bbd 86 *{ __PACKAGE__ . '::' . "add_${modifier_type}_method_modifier" } = sub {
87 my ($self, $method_name, $method) = @_;
88
89 push @{ $self->{"${modifier_type}_method_modifiers"}->{$method_name} },
90 $method;
91 };
92
c2f128e7 93 *{ __PACKAGE__ . '::' . "get_${modifier_type}_method_modifiers" } = sub {
94 my ($self, $method_name, $method) = @_;
95 @{ $self->{"${modifier_type}_method_modifiers"}->{$method_name} || [] }
96 };
97}
98
a2227e71 991;
100