Checking in changes prior to tagging of version 0.71.
[gitmo/Mouse.git] / lib / Mouse / Meta / Method / Delegation.pm
1 package Mouse::Meta::Method::Delegation;
2 use Mouse::Util qw(:meta); # enables strict and warnings
3 use Scalar::Util;
4
5 sub _generate_delegation{
6     my (undef, $attr, $handle_name, $method_to_call) = @_;
7
8     my @curried_args;
9     if(ref($method_to_call) eq 'ARRAY'){
10         ($method_to_call, @curried_args) = @{$method_to_call};
11     }
12
13     # If it has a reader, we must use it to make method modifiers work
14     my $reader = $attr->get_read_method() || $attr->get_read_method_ref();
15
16     my $can_be_optimized = $attr->{_method_delegation_can_be_optimized};
17
18     if(!defined $can_be_optimized){
19         my $tc = $attr->type_constraint;
20
21         $attr->{_method_delegation_can_be_optimized} =
22             (defined($tc) && $tc->is_a_type_of('Object'))
23             && ($attr->is_required || $attr->has_default || $attr->has_builder)
24             && ($attr->is_lazy || !$attr->has_clearer);
25     }
26
27     if($can_be_optimized){
28         # need not check the attribute value
29         return sub {
30             return shift()->$reader()->$method_to_call(@curried_args, @_);
31         };
32     }
33     else {
34         # need to check the attribute value
35         return sub {
36             my $instance = shift;
37             my $proxy    = $instance->$reader();
38
39             my $error = !defined($proxy)                              ? ' is not defined'
40                       : ref($proxy) && !Scalar::Util::blessed($proxy) ? qq{ is not an object (got '$proxy')}
41                                                                       : undef;
42             if ($error) {
43                 $instance->meta->throw_error(
44                     "Cannot delegate $handle_name to $method_to_call because "
45                         . "the value of "
46                         . $attr->name
47                         . $error
48                  );
49             }
50             $proxy->$method_to_call(@curried_args, @_);
51         };
52     }
53 }
54
55
56 1;
57 __END__
58
59 =head1 NAME
60
61 Mouse::Meta::Method::Delegation - A Mouse method generator for delegation methods
62
63 =head1 VERSION
64
65 This document describes Mouse version 0.71
66
67 =head1 SEE ALSO
68
69 L<Moose::Meta::Method::Delegation>
70
71 =cut