Commit | Line | Data |
---|---|---|
e601adda | 1 | package Catalyst::Action::Serialize::JSON; |
2 | ||
930013e6 | 3 | use Moose; |
4 | use namespace::autoclean; | |
8d507a2f | 5 | BEGIN { |
6 | $ENV{'PERL_JSON_BACKEND'} = 2; # Always use compiled JSON::XS | |
7 | } | |
e601adda | 8 | |
930013e6 | 9 | extends 'Catalyst::Action'; |
14cbe8f1 | 10 | use JSON (); |
e601adda | 11 | |
8004a60b | 12 | our $VERSION = '1.00'; |
f465980c | 13 | $VERSION = eval $VERSION; |
14 | ||
14cbe8f1 | 15 | has encoder => ( |
16 | is => 'ro', | |
17 | lazy_build => 1, | |
18 | ); | |
19 | ||
20 | sub _build_encoder { | |
21 | my $self = shift; | |
22 | return JSON->new->utf8->convert_blessed; | |
23 | } | |
24 | ||
e601adda | 25 | sub execute { |
26 | my $self = shift; | |
27 | my ( $controller, $c ) = @_; | |
28 | ||
faf5c20b | 29 | my $stash_key = ( |
07682cbc | 30 | $controller->{'serialize'} ? |
31 | $controller->{'serialize'}->{'stash_key'} : | |
14cbe8f1 | 32 | $controller->{'stash_key'} |
faf5c20b | 33 | ) || 'rest'; |
7f36b63e | 34 | my $output = $self->serialize( $c->stash->{$stash_key} ); |
e601adda | 35 | $c->response->output( $output ); |
36 | return 1; | |
37 | } | |
38 | ||
485b5160 | 39 | sub serialize { |
546f2871 | 40 | my $self = shift; |
14cbe8f1 | 41 | my $data = shift; |
42 | $self->encoder->encode( $data ); | |
546f2871 | 43 | } |
44 | ||
24748286 | 45 | __PACKAGE__->meta->make_immutable; |
46 | ||
e601adda | 47 | 1; |