Skip to content

Instantly share code, notes, and snippets.

@jberger
Created May 8, 2017 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/687fff38763e70b6712975f6aea8779c to your computer and use it in GitHub Desktop.
Save jberger/687fff38763e70b6712975f6aea8779c to your computer and use it in GitHub Desktop.
use Mojo::Base -strict;
{
package Mojolicious::Plugin::JSONPretty;
use Mojo::Base 'Mojolicious::Plugin';
use JSON::MaybeXS;
# stolen from Mojo::JSON::MaybeXS
my $JSON = JSON::MaybeXS->new(
utf8 => 1,
canonical => 1,
allow_nonref => 1,
allow_unknown => 1,
allow_blessed => 1,
convert_blessed => 1,
pretty => 1,
);
sub register {
my ($plugin, $app, $conf) = @_;
$app->renderer->add_handler(json_pretty => sub {
my ($renderer, $c, $output, $options) = @_;
# Disable automatic encoding
delete $options->{encoding};
# Encode data from stash value
$$output = $JSON->encode(delete $c->stash->{json_pretty});
# add headers
$c->res->headers->content_type('application/json;charset=UTF-8');
});
my $always = $conf->{always} || $app->config->{json_pretty};
$app->hook(before_render => sub {
my ($c, $args) = @_;
return $args->{handler} = 'json_pretty'
if exists $args->{json_pretty} || exists $c->stash->{json_pretty};
return unless $always && (exists $args->{json} || exists $c->stash->{json});
# strongly prevent json default handling,
# args wins out but remove json stash value too
$args->{json_pretty} = delete $c->stash->{json};
$args->{json_pretty} = delete $args->{json} if $args->{json};
$args->{handler} = 'json_pretty';
});
}
}
use Mojolicious::Lite;
#plugin Config => {
#default => {
#json_pretty => 1,
#},
#};
plugin 'JSONPretty';
#plugin 'JSONPretty', {always => 1};
my $data = {hello => 'world', testing => [1..3]};
any '/' => { json => $data };
any '/pretty' => { json_pretty => $data };
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment