Added Test Suite
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Action / Serialize.pm
CommitLineData
7ad87df9 1#
2# Catlyst::Action::Serialize.pm
3# Created by: Adam Jacob, Marchex, <adam@marchex.com>
4#
5# $Id$
6
7package Catalyst::Action::Serialize;
8
9use strict;
10use warnings;
11
12use base 'Catalyst::Action';
13use Module::Pluggable::Object;
14
15__PACKAGE__->mk_accessors(qw(plugins));
16
17sub execute {
18 my $self = shift;
19 my ( $controller, $c ) = @_;
20
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)$/;
25
26 # Load the Serialize Classes
27 unless(defined($self->plugins)) {
28 my $mpo = Module::Pluggable::Object->new(
29 'require' => 1,
30 'search_path' => [ 'Catalyst::Action::Serialize' ],
31 );
32 my @plugins = $mpo->plugins;
33 $self->plugins(\@plugins);
34 }
35
36 # Look up what serializer to use from content_type map
37 #
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::';
41 my $sarg;
42 my $map = $controller->serialize->{'map'};
43 if (exists($map->{$content_type})) {
44 my $mc;
45 if (ref($map->{$content_type}) eq "ARRAY") {
46 $mc = $map->{$content_type}->[0];
47 $sarg = $map->{$content_type}->[1];
48 } else {
49 $mc = $map->{$content_type};
50 }
51 $sclass .= $mc;
52 if (! grep(/^$sclass$/, @{$self->plugins})) {
53 die "Cannot find plugin $sclass for $content_type!";
54 }
55 } else {
56 if (exists($controller->serialize->{'default'})) {
57 $sclass .= $controller->serialize->{'default'};
58 } else {
59 die "I cannot find a default serializer!";
60 }
61 }
62
63 # Go ahead and serialize ourselves
64 if (defined($sarg)) {
65 $sclass->execute($controller, $c, $sarg);
66 } else {
67 $sclass->execute($controller, $c);
68 }
69
70 if (! $c->response->content_type ) {
71 $c->response->content_type($c->request->content_type);
72 }
73
74 return 1;
75};
76
771;