File Coverage

blib/lib/Dancer2/Plugin/Ajax.pm
Criterion Covered Total %
statement 28 28 100.0
branch 6 10 60.0
condition 1 2 50.0
subroutine 5 5 100.0
pod n/a
total 40 45 88.8


line stmt bran cond sub pod time code
1             package Dancer2::Plugin::Ajax;
2             # ABSTRACT: a plugin for adding Ajax route handlers
3             $Dancer2::Plugin::Ajax::VERSION = '0.200001';
4 1     1   449518 use strict;
  1         3  
  1         27  
5 1     1   5 use warnings;
  1         2  
  1         26  
6 1     1   746 use Dancer2::Plugin;
  1         2372  
  1         7  
7              
8             register 'ajax' => sub {
9 3     3   7224 my ( $dsl, $pattern, @rest ) = @_;
10              
11 3         9 my $default_methods = [ 'get', 'post' ];
12              
13             # If the given pattern is an ArrayRef, we override the defaults
14             # and pass these onto to DSL->any()
15 3 100       11 if( ref($pattern) eq "ARRAY" ) {
16 1         3 $default_methods = $pattern;
17 1         3 $pattern = shift(@rest);
18             }
19              
20 3         5 my $code;
21 3 50       6 for my $e (@rest) { $code = $e if ( ref($e) eq 'CODE' ) }
  3         12  
22              
23 3   50     13 my $content_type = plugin_setting->{content_type} || 'text/xml';
24              
25             my $ajax_route = sub {
26              
27             # # must be an XMLHttpRequest
28 7 100   7   159683 if ( not $dsl->app->request->is_ajax ) {
29 2 0       359 $dsl->pass and return 0;
30             }
31              
32             # Default response content type is either what's defined in the
33             # plugin setting or text/xml
34 5 50       1119 $dsl->response->header('Content-Type')
35             or $dsl->response->content_type( $content_type );
36              
37             # disable layout
38 5         2734 my $layout = $dsl->setting('layout');
39 5         469 $dsl->setting( 'layout' => undef );
40 5         1584 my $response = $code->();
41 5         30 $dsl->setting( 'layout' => $layout );
42 5         913 return $response;
43 3         248 };
44              
45 3         17 $dsl->any( $default_methods => $pattern, $ajax_route );
46             };
47              
48             register_plugin;
49              
50             1;
51              
52             __END__