File Coverage

blib/lib/Kelp/Module/JSON.pm
Criterion Covered Total %
statement 12 12 100.0
branch n/a
condition n/a
subroutine 5 5 100.0
pod 1 3 33.3
total 18 20 90.0


line stmt bran cond sub pod time code
1             package Kelp::Module::JSON;
2              
3 34     34   21545 use Kelp::Base 'Kelp::Module::Encoder';
  34         73  
  34         305  
4              
5 34     34   17721 use JSON::MaybeXS;
  34         319900  
  34         7728  
6              
7 100     100 0 522 sub encoder_name { 'json' }
8              
9             sub build_encoder
10             {
11 55     55 0 176 my ($self, $args) = @_;
12 55         429 return JSON::MaybeXS->new(%$args);
13             }
14              
15             sub build
16             {
17 45     45 1 165 my ($self, %args) = @_;
18 45         391 $self->SUPER::build(%args);
19              
20 45         254 $self->register(json => $self->get_encoder);
21             }
22              
23             1;
24              
25             __END__
26              
27             =head1 NAME
28              
29             Kelp::Module::JSON - Simple JSON module for a Kelp application
30              
31             =head1 SYNOPSIS
32              
33             package MyApp;
34             use Kelp::Base 'Kelp';
35              
36             sub some_route {
37             my $self = shift;
38              
39             # manually render a json configured to UTF-8
40             $self->res->set_charset('UTF-8');
41             $self->res->render_binary(
42             $self->json->encode({ yes => 1 })
43             );
44             }
45              
46             =head1 DESCRIPTION
47              
48             Standard JSON encoder/decoder. Chooses the best backend through L<JSON::MaybeXS>.
49              
50             =head1 REGISTERED METHODS
51              
52             This module registers only one method into the application: C<json>. It also
53             registers itself for later use by L<Kelp/get_encoder> under the name C<json>.
54              
55             The module will try to use backends in this order: I<Cpanel::JSON::XS, JSON::XS, JSON::PP>.
56              
57             =head1 CAVEATS
58              
59             You should probably not use C<utf8>, and just encode the value into a proper
60             charset by hand. You may not always want to have encoded strings anyway, for
61             example some interfaces may encode the values themselves.
62              
63             Kelp will use an internal copy of JSON encoder / decoder with all the same options
64             but without C<utf8>, reserved for internal use. Modifying C<json> options at
65             runtime will not cause the request / response encoding to change.
66              
67             =cut
68