fix a memory leak introduced by 1f8cad5e5a1875de94d63ac91d8ded4d2282c62e
[catagits/Web-Simple.git] / lib / Web / Dispatch.pm
index e32aced..d34fe6e 100644 (file)
@@ -14,14 +14,13 @@ with 'Web::Dispatch::ToApp';
 has dispatch_app => (
   is => 'lazy', builder => sub { shift->dispatch_object->to_app }
 );
-has dispatch_object => (is => 'ro', required => 0);
+has dispatch_object => (is => 'ro', required => 0, weak_ref => 1);
 has parser_class => (
   is => 'ro', default => quote_sub q{ 'Web::Dispatch::Parser' }
 );
 has node_class => (
   is => 'ro', default => quote_sub q{ 'Web::Dispatch::Node' }
 );
-has node_args => (is => 'ro', default => quote_sub q{ {} });
 has _parser => (is => 'lazy');
 
 after BUILDARGS => sub {
@@ -127,7 +126,11 @@ sub _to_try {
     } else {
       $try
     }
-  } elsif (!ref($try) and ref($more->[0]) eq 'CODE') {
+  } elsif (!ref($try)
+    and (ref($more->[0]) eq 'CODE'
+      or (!ref($more->[0]) and $self->dispatch_object
+        and $self->dispatch_object->can($more->[0])))
+  ) {
     $self->_construct_node(match => $try, run => shift(@$more));
   } elsif (
     (blessed($try) && $try->isa('Web::Dispatch::Matcher'))
@@ -144,7 +147,12 @@ sub _to_try {
 sub _construct_node {
   my ($self, %args) = @_;
   $args{match} = $self->_parser->parse($args{match}) if !ref $args{match};
-  $self->node_class->new({ %{$self->node_args}, %args })->to_app;
+  if ( my $obj = $self->dispatch_object) {
+    # if possible, call dispatchers as methods of the app object
+    my $dispatch_sub = $args{run};
+    $args{run} = sub { $obj->$dispatch_sub(@_) };
+  }
+  $self->node_class->new(\%args)->to_app;
 }
 
 1;