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