Permalink
Browse files

add Dancer::Serializer::JSONP

subclass of Dancer::Serializer::JSON with support for JSONP
  • Loading branch information...
1 parent 029b82a commit affce58bfe6b56273a38a90f2748593a05846cac @zurborg zurborg committed with yanick Jun 17, 2014
Showing with 41 additions and 0 deletions.
  1. +20 −0 lib/Dancer/Serializer/JSONP.pm
  2. +21 −0 t/14_serializer/07_request_jsonp.t
@@ -0,0 +1,20 @@
+package Dancer::Serializer::JSONP;
+
+use strict;
+use warnings;
+use Dancer::SharedData;
+use parent 'Dancer::Serializer::JSON';
+
+sub serialize {
+ my $self = shift;
+
+ my $callback = Dancer::SharedData->request->params('query')->{callback};
+
+ my $json = $self->SUPER::serialize(@_);
+
+ return $callback . '(' . $json . ');';
+}
+
+sub content_type {'application/javascript'}
+
+1;
@@ -0,0 +1,21 @@
+use Test::More import => ['!pass'];
+use strict;
+use warnings;
+use Dancer ':tests';
+use Dancer::Test;
+
+BEGIN {
+ plan skip_all => "need JSON"
+ unless Dancer::ModuleLoader->load('JSON');
+
+ plan tests => 2;
+}
+
+set 'serializer' => 'JSONP', 'show_errors' => 1;
+
+get '/' => sub { { foo => 'bar' } };
+
+my $res = dancer_response( GET => '/' , { params => { callback => 'func' } } );
+is $res->header('Content-Type'), 'application/javascript';
+like $res->content, qr/func\( \s* \{ \s* "foo" \s* : \s* "bar" \s* \} \s* \); /mix;
+

0 comments on commit affce58

Please sign in to comment.