Make saner
t0m [Sun, 5 Jul 2009 13:12:58 +0000 (14:12 +0100)]
lib/Catalyst/Action/REST.pm

index cf803d6..e9ca9b0 100644 (file)
@@ -90,25 +90,35 @@ sub dispatch {
     my $c    = shift;
 
     my $controller = $c->component( $self->class );
-    my $method     = $self->name . "_" . uc( $c->request->method );
+    my $rest_method = $self->name . "_" . uc( $c->request->method );
 
-    if (my $code = $controller->can($method)) {
-        $c->execute( $self->class, $self, @{ $c->req->args } ) if $code;
-        local $self->{reverse} = $self->{reverse} . "_" . uc( $c->request->method );
-        local $self->{code} = $code;
+    my ($code, $name);
 
-        return $c->execute( $self->class, $self, @{ $c->req->args } );
+    # Common case, for foo_GET etc
+    if ($code = $controller->can($rest_method)) {
+        # Exceute normal action
+        $c->execute( $self->class, $self, @{ $c->req->args } );
+        $name = $rest_method;
     }
-    if ($c->request->method eq "OPTIONS") {
-        local $self->{reverse} = $self->{reverse} . "_" . uc( $c->request->method );
-        local $self->{code} = sub { $self->can('_return_options')->($self->name, @_) };
-        return $c->execute( $self->class, $self, @{ $c->req->args } );
+
+    # Generic handling for foo_OPTIONS
+    if (!$code && $c->request->method eq "OPTIONS") {
+        $name = $rest_method;
+        $code = sub { $self->_return_options($self->name, @_) };
+    }
+
+    # Otherwise, not implemented.
+    if (!$code) {
+        $name = $self->name . "_not_implemented";
+        $code = $controller->can($name) # User method
+            # Generic not implemented
+            || sub { $self->_return_not_implemented($self->name, @_) };
     }
-    my $not_implemented_method = $self->name . "_not_implemented";
-    local $self->{code} = $controller->can($not_implemented_method)
-        || sub { $self->can('_return_not_implemented')->($self->name, @_); };
 
-    local $self->{reverse} = $not_implemented_method;
+    # localise stuff so we can dispatch the action 'as normal, but get
+    # different stats shown, and different code run.
+    local $self->{code} = $code;
+    local $self->{reverse} = $name;
 
     $c->execute( $self->class, $self, @{ $c->req->args } );
 }
@@ -127,7 +137,7 @@ my $_get_allowed_methods = sub {
 };
 
 sub _return_options {
-    my ( $method_name, $controller, $c) = @_;
+    my ( $self, $method_name, $controller, $c) = @_;
     my @allowed = $controller->$_get_allowed_methods($c, $method_name);
     $c->response->content_type('text/plain');
     $c->response->status(200);
@@ -135,7 +145,7 @@ sub _return_options {
 }
 
 sub _return_not_implemented {
-    my ( $method_name, $controller, $c ) = @_;
+    my ( $self, $method_name, $controller, $c ) = @_;
 
     my @allowed = $controller->$_get_allowed_methods($c, $method_name);
     $c->response->content_type('text/plain');