Commit | Line | Data |
---|---|---|
e601adda | 1 | package Catalyst::Action::Serialize::JSON; |
2 | ||
930013e6 | 3 | use Moose; |
4 | use namespace::autoclean; | |
e601adda | 5 | |
930013e6 | 6 | extends 'Catalyst::Action'; |
aadb0c7d | 7 | use JSON::MaybeXS qw(JSON); |
e601adda | 8 | |
14cbe8f1 | 9 | has encoder => ( |
10 | is => 'ro', | |
11 | lazy_build => 1, | |
12 | ); | |
13 | ||
14 | sub _build_encoder { | |
15 | my $self = shift; | |
16 | return JSON->new->utf8->convert_blessed; | |
17 | } | |
18 | ||
e601adda | 19 | sub execute { |
20 | my $self = shift; | |
21 | my ( $controller, $c ) = @_; | |
22 | ||
43e4baa3 | 23 | if (my $options = $controller->{json_options_encode}) { |
24 | foreach my $opt (keys %$options) { | |
25 | $self->encoder->$opt( $options->{$opt} ); | |
26 | } | |
27 | } | |
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; |