Make method body load lazily
Scott McWhirter [Fri, 26 Jun 2009 01:25:58 +0000 (02:25 +0100)]
lib/Class/MOP.pm
lib/Class/MOP/Method/Accessor.pm
lib/Class/MOP/Method/Generated.pm

index 7da9660..5ac9773 100644 (file)
@@ -517,7 +517,8 @@ Class::MOP::Attribute->meta->add_method('clone' => sub {
 ## Class::MOP::Method
 Class::MOP::Method->meta->add_attribute(
     Class::MOP::Attribute->new('body' => (
-        reader   => { 'body' => \&Class::MOP::Method::body },
+        lazy => 1,
+        default => \&Class::MOP::Method::body,
     ))
 );
 
index 3891fd0..6dfd22c 100644 (file)
@@ -36,8 +36,6 @@ sub new {
     # needed
     weaken($self->{'attribute'});
 
-    $self->_initialize_body;
-
     return $self;
 }
 
index 056bc77..d717f83 100644 (file)
@@ -28,6 +28,16 @@ sub _initialize_body {
     confess "No body to initialize, " . __PACKAGE__ . " is an abstract base class";
 }
 
+sub body {
+    my $self = shift;
+
+    $self->{'body'} ||= do {
+       $self->_initialize_body; 
+    };
+
+    return $self->{'body'};
+}
+
 sub _eval_closure {
     # my ($self, $captures, $sub_body) = @_;
     my $__captures = $_[1];