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