Added logging to 4xx status handlers
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Action / REST.pm
CommitLineData
256c894f 1#
2# REST.pm
3# Created by: Adam Jacob, Marchex, <adam@marchex.com>
4# Created on: 10/12/2006 03:00:32 PM PDT
5#
6# $Id$
7
8package Catalyst::Action::REST;
9
10use strict;
11use warnings;
12
13use base 'Catalyst::Action';
7ad87df9 14use Class::Inspector;
7328f0ab 15use 5.8.1;
256c894f 16
7328f0ab 17my
18$VERSION = '0.1';
19
20=head1 NAME
21
22Catalyst::Action::REST - Automated REST Method Dispatching
23
24=head1 SYNOPSIS
25
26 sub foo :Local :ActionClass('REST') {}
27
28 sub foo_GET {
29 ... do something for GET requests ...
30 }
31
32 sub foo_PUT {
33 ... do somethign for PUT requests ...
34 }
35
36=head1 DESCRIPTION
37
38This Action handles doing automatic method dispatching for REST requests. It
39takes a normal Catalyst action, and changes the dispatch to append an
40underscore and method name.
41
42For example, in the synopsis above, calling GET on "/foo" would result in
43the foo_GET method being dispatched.
44
45If a method is requested that is not implemented, this action will
46return a status 405 (Method Not Found). It will populate the "Allow" header
47with the list of implemented request methods.
48
49=head1 METHODS
50
51=over 4
52
53=item dispatch
54
55This method overrides the default dispatch mechanism to the re-dispatching
56mechanism described above.
57
58=cut
256c894f 59sub dispatch {
bb4130f6 60 my $self = shift;
61 my $c = shift;
256c894f 62
63 my $controller = $self->class;
eccb2137 64 my $method = $self->name . "_" . uc( $c->request->method );
65 if ( $controller->can($method) ) {
bb4130f6 66 return $controller->$method($c, @{$c->req->args});
256c894f 67 } else {
7ad87df9 68 $self->_return_405($c);
bb4130f6 69 return $c->execute( $self->class, $self, @{$c->req->args} );
256c894f 70 }
71}
72
7ad87df9 73sub _return_405 {
74 my ( $self, $c ) = @_;
75
76 my $controller = $self->class;
eccb2137 77 my $methods = Class::Inspector->methods($controller);
7ad87df9 78 my @allowed;
eccb2137 79 foreach my $method ( @{$methods} ) {
7ad87df9 80 my $name = $self->name;
eccb2137 81 if ( $method =~ /^$name\_(.+)$/ ) {
82 push( @allowed, $1 );
7ad87df9 83 }
84 }
85 $c->response->content_type('text/plain');
86 $c->response->status(405);
eccb2137 87 $c->response->header( 'Allow' => \@allowed );
88 $c->response->body( "Method "
89 . $c->request->method
90 . " not implemented for "
91 . $c->uri_for( $self->reverse ) );
7ad87df9 92}
93
256c894f 941;
7328f0ab 95
96=back
97
98=head1 SEE ALSO
99
100You likely want to look at L<Catalyst::Controller::REST>, which implements
101a sensible set of defaults for a controller doing REST.
102
103L<Catalyst::Action::Serialize>, L<Catalyst::Action::Deserialize>
104
105=head1 AUTHOR
106
107Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
108
109=head1 LICENSE
110
111You may distribute this code under the same terms as Perl itself.
112
113=cut