Adding basic pod to Catalyst::Action::REST
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Action / REST.pm
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
8 package Catalyst::Action::REST;
9
10 use strict;
11 use warnings;
12
13 use base 'Catalyst::Action';
14 use Class::Inspector;
15 use 5.8.1;
16
17 my 
18 $VERSION = '0.1';
19
20 =head1 NAME
21
22 Catalyst::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
38 This Action handles doing automatic method dispatching for REST requests.  It
39 takes a normal Catalyst action, and changes the dispatch to append an
40 underscore and method name. 
41
42 For example, in the synopsis above, calling GET on "/foo" would result in
43 the foo_GET method being dispatched.
44
45 If a method is requested that is not implemented, this action will 
46 return a status 405 (Method Not Found).  It will populate the "Allow" header 
47 with the list of implemented request methods.
48
49 =head1 METHODS
50
51 =over 4
52
53 =item dispatch
54
55 This method overrides the default dispatch mechanism to the re-dispatching
56 mechanism described above.
57
58 =cut
59 sub dispatch {
60     my ( $self, $c ) = @_;
61
62     my $controller = $self->class;
63     my $method     = $self->name . "_" . uc( $c->request->method );
64     if ( $controller->can($method) ) {
65         return $controller->$method($c);
66     } else {
67         $self->_return_405($c);
68         return $c->execute( $self->class, $self );
69     }
70 }
71
72 sub _return_405 {
73     my ( $self, $c ) = @_;
74
75     my $controller = $self->class;
76     my $methods    = Class::Inspector->methods($controller);
77     my @allowed;
78     foreach my $method ( @{$methods} ) {
79         my $name = $self->name;
80         if ( $method =~ /^$name\_(.+)$/ ) {
81             push( @allowed, $1 );
82         }
83     }
84     $c->response->content_type('text/plain');
85     $c->response->status(405);
86     $c->response->header( 'Allow' => \@allowed );
87     $c->response->body( "Method "
88           . $c->request->method
89           . " not implemented for "
90           . $c->uri_for( $self->reverse ) );
91 }
92
93 1;
94
95 =back
96
97 =head1 SEE ALSO
98
99 You likely want to look at L<Catalyst::Controller::REST>, which implements
100 a sensible set of defaults for a controller doing REST.
101
102 L<Catalyst::Action::Serialize>, L<Catalyst::Action::Deserialize>
103
104 =head1 AUTHOR
105
106 Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
107
108 =head1 LICENSE
109
110 You may distribute this code under the same terms as Perl itself.
111
112 =cut