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.3514_04'; # TRIAL
5             $Dancer::Plugin::Ajax::VERSION = '1.351404';
6 2     2   60657 use strict;
  2         17  
  2         55  
7 2     2   11 use warnings;
  2         4  
  2         61  
8              
9 2     2   603 use Dancer ':syntax';
  2         4  
  2         13  
10 2     2   18 use Dancer::Exception ':all';
  2         6  
  2         251  
11 2     2   956 use Dancer::Plugin;
  2         5  
  2         617  
12              
13             register 'ajax' => \&ajax;
14              
15             hook before => sub {
16             if (request->is_ajax) {
17             content_type( plugin_setting->{content_type} || 'text/xml' );
18             }
19             };
20              
21             sub ajax {
22 1     1   3 my ($pattern, @rest) = @_;
23              
24 1         2 my $code;
25 1 50       2 for my $e (@rest) { $code = $e if (ref($e) eq 'CODE') }
  1         4  
26              
27             my $ajax_route = sub {
28             # must be an XMLHttpRequest
29 0 0   0   0 if (not request->is_ajax) {
30 0 0       0 pass and return 0;
31             }
32              
33             # disable layout
34 0         0 my $layout = setting('layout');
35 0         0 setting('layout' => undef);
36             my $response = try {
37 0         0 $code->();
38             } catch {
39 0         0 my $e = $_;
40 0         0 setting('layout' => $layout);
41 0         0 die $e;
42 0         0 };
43 0         0 setting('layout' => $layout);
44 0         0 return $response;
45 1         5 };
46              
47             # rebuild the @rest array with the compiled route handler
48 1         1 my @compiled_rest;
49 1         2 for my $e (@rest) {
50 1 50       4 if (ref($e) eq 'CODE') {
51 1         3 push @compiled_rest, {ajax => 1}, $ajax_route;
52             }
53             else {
54 0         0 push @compiled_rest, {ajax => 1}, $e;
55             }
56             }
57              
58 1         5 any ['get', 'post'] => $pattern, @compiled_rest;
59             }
60              
61             register_plugin;
62             1;
63              
64             __END__