File Coverage

lib/Dancer/Plugin/Ajax.pm
Criterion Covered Total %
statement 25 37 67.5
branch 2 8 25.0
condition n/a
subroutine 6 7 85.7
pod n/a
total 33 52 63.4


line stmt bran cond sub pod time code
1             package Dancer::Plugin::Ajax;
2             our $AUTHORITY = 'cpan:SUKRIA';
3             #ABSTRACT: a plugin for adding Ajax route handlers
4             $Dancer::Plugin::Ajax::VERSION = '1.3520';
5 2     2   68306 use strict;
  2         12  
  2         61  
6 2     2   13 use warnings;
  2         5  
  2         65  
7              
8 2     2   642 use Dancer ':syntax';
  2         8  
  2         10  
9 2     2   15 use Dancer::Exception ':all';
  2         5  
  2         269  
10 2     2   982 use Dancer::Plugin;
  2         7  
  2         817  
11              
12             register 'ajax' => \&ajax;
13              
14             hook before => sub {
15             if (request->is_ajax) {
16             content_type( plugin_setting->{content_type} || 'text/xml' );
17             }
18             };
19              
20             sub ajax {
21 1     1   6 my ($pattern, @rest) = @_;
22              
23 1         4 my $code;
24 1 50       4 for my $e (@rest) { $code = $e if (ref($e) eq 'CODE') }
  1         24  
25              
26             my $ajax_route = sub {
27             # must be an XMLHttpRequest
28 0 0   0   0 if (not request->is_ajax) {
29 0 0       0 pass and return 0;
30             }
31              
32             # disable layout
33 0         0 my $layout = setting('layout');
34 0         0 setting('layout' => undef);
35             my $response = try {
36 0         0 $code->();
37             } catch {
38 0         0 my $e = $_;
39 0         0 setting('layout' => $layout);
40 0         0 die $e;
41 0         0 };
42 0         0 setting('layout' => $layout);
43 0         0 return $response;
44 1         13 };
45              
46             # rebuild the @rest array with the compiled route handler
47 1         70 my @compiled_rest;
48 1         6 for my $e (@rest) {
49 1 50       9 if (ref($e) eq 'CODE') {
50 1         9 push @compiled_rest, {ajax => 1}, $ajax_route;
51             }
52             else {
53 0         0 push @compiled_rest, {ajax => 1}, $e;
54             }
55             }
56              
57 1         32 any ['get', 'post'] => $pattern, @compiled_rest;
58             }
59              
60             register_plugin;
61             1;
62              
63             __END__