2 # Catlyst::Action::Serialize.pm
3 # Created by: Adam Jacob, Marchex, <adam@marchex.com>
7 package Catalyst::Action::Serialize;
12 use base 'Catalyst::Action';
13 use Module::Pluggable::Object;
15 __PACKAGE__->mk_accessors(qw(plugins));
19 my ( $controller, $c ) = @_;
21 return 1 if $c->req->method eq 'HEAD';
22 return 1 if length( $c->response->body );
23 return 1 if scalar @{ $c->error };
24 return 1 if $c->response->status =~ /^(?:204|3\d\d)$/;
26 # Load the Serialize Classes
27 unless ( defined( $self->plugins ) ) {
28 my $mpo = Module::Pluggable::Object->new(
30 'search_path' => ['Catalyst::Action::Serialize'],
32 my @plugins = $mpo->plugins;
33 $self->plugins( \@plugins );
36 # Look up what serializer to use from content_type map
38 # If we don't find one, we use the default
39 my $content_type = $c->request->content_type;
40 my $sclass = 'Catalyst::Action::Serialize::';
42 my $map = $controller->serialize->{'map'};
43 if ( exists( $map->{$content_type} ) ) {
45 if ( ref( $map->{$content_type} ) eq "ARRAY" ) {
46 $mc = $map->{$content_type}->[0];
47 $sarg = $map->{$content_type}->[1];
49 $mc = $map->{$content_type};
52 if ( !grep( /^$sclass$/, @{ $self->plugins } ) ) {
53 die "Cannot find plugin $sclass for $content_type!";
56 if ( exists( $controller->serialize->{'default'} ) ) {
57 $sclass .= $controller->serialize->{'default'};
59 die "I cannot find a default serializer!";
63 # Go ahead and serialize ourselves
64 if ( defined($sarg) ) {
65 $sclass->execute( $controller, $c, $sarg );
67 $sclass->execute( $controller, $c );
70 if ( !$c->response->content_type ) {
71 $c->response->content_type( $c->request->content_type );
81 Catalyst::Action::Serialize - Serialize Data in a Response
85 package Foo::Controller::Bar;
90 'stash_key' => 'rest',
92 'text/x-yaml' => 'YAML',
93 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
98 sub end : ActionClass('Serialize') {}
102 This action will serialize the body of an HTTP Response. The serializer is
103 selected by introspecting the requests content-type header.
105 It requires that your Catalyst controller have a "serialize" entry
106 in it's configuration.
108 The specifics of serializing each content-type is implemented as
109 a plugin to L<Catalyst::Action::Serialize>.
117 The default Serialization format. See the next section for
118 available options. This is used if a requested content-type
123 Where in the stash the data you want serialized lives.
127 Takes a hashref, mapping Content-Types to a given plugin.
133 You likely want to look at L<Catalyst::Controller::REST>, which implements
134 a sensible set of defaults for a controller doing REST.
136 L<Catalyst::Action::Deserialize>, L<Catalyst::Action::REST>
140 Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
142 Marchex, Inc. paid me while I developed this module. (http://www.marchex.com)
146 You may distribute this code under the same terms as Perl itself.