Permalink
Browse files

new has_json support method

Added has_json support method to help determine if JSON data is
in play. The method works for both header & body data.
  • Loading branch information...
1 parent e04fbed commit 341af4347a91027ef4f289fa1d39d159d6e2034b Jason Purdy committed Jul 8, 2010
Showing with 45 additions and 1 deletion.
  1. +24 −0 lib/CGI/Application/Plugin/JSON.pm
  2. +15 −1 t/02-json.t
  3. +6 −0 t/lib/MyApp.pm
@@ -12,6 +12,7 @@ our @EXPORT_OK = qw(
json_callback
add_json_header
clear_json_header
+ has_json
json_header_string
json_header_value
);
@@ -43,6 +44,9 @@ our $VERSION = '1.01';
# clear out everything in the outgoing JSON headers
$self->clear_json_header();
+
+ # check to see if there's a JSON header or body in play
+ return if $self->has_json();
# or send the JSON in the document body
$self->json_body( { foo => 'Lorem ipsum', bar => [ 0, 2, 3 ] } );
@@ -117,6 +121,26 @@ sub clear_json_header {
$self->param('__CAP_JSON' => $private);
}
+=head2 has_json
+
+This method will check to see if there's a JSON header (or body) in play
+and return true. This is useful in the case of wanting to skip shell
+templates in a generic cgiapp_postrun method:
+
+ sub cgiapp_postrun {
+ my ( $self, $output_ref ) = @_;
+ return if $self->has_json();
+ # proceed w/ shell...
+ }
+
+=cut
+
+sub has_json {
+ my $self = shift;
+ my $has_json = ( $self->param('__CAP_JSON') ) ? 1 : 0;
+ return $has_json;
+}
+
=head2 json_header_string
This method will create the actual HTTP header string that will be sent
View
@@ -5,7 +5,7 @@ use JSON::Any;
use lib 't/lib';
use MyApp;
-plan(tests => 21);
+plan(tests => 24);
$ENV{'CGI_APP_RETURN_ONLY'} = 1;
@@ -70,6 +70,20 @@ $ENV{'CGI_APP_RETURN_ONLY'} = 1;
is_deeply($json, { foo => 'blah', baz => 'stuff', bar => 'more_stuff'});
}
+# 22-24
+# has_json
+{
+ my $app = MyBase::MyApp->new( QUERY => CGI->new({ rm => 'test_json' }) );
+ my $output = $app->run();
+ is( $app->has_json(), 1, 'has_json found data in header' );
+ $app = MyBase::MyApp->new( QUERY => CGI->new({ rm => 'test_body' }) );
+ $output = $app->run();
+ is( $app->has_json(), 1, 'has_json found data in body' );
+ $app = MyBase::MyApp->new( QUERY => CGI->new({ rm => 'test_nojson' }) );
+ $output = $app->run();
+ is( $app->has_json(), 0, 'has_json did not find data' );
+}
+
# has 2 tests
sub _get_json_data {
my $app = shift;
View
@@ -11,6 +11,7 @@ sub setup {
test_clear
test_body
test_callback
+ test_nojson
)]);
$self->start_mode('test_json');
@@ -61,4 +62,9 @@ sub test_callback {
);
}
+sub test_nojson {
+ my $self = shift;
+ return 'Hello world!';
+}
+
1;

0 comments on commit 341af43

Please sign in to comment.