File Coverage

blib/lib/Dancer2/Plugin/Ajax.pm
Criterion Covered Total %
statement 31 31 100.0
branch 6 8 75.0
condition n/a
subroutine 6 6 100.0
pod 0 1 0.0
total 43 46 93.4


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.400000';
4 1     1   805154 use strict;
  1         9  
  1         30  
5 1     1   6 use warnings;
  1         2  
  1         27  
6 1     1   5 use Dancer2::Core::Types 'Str';
  1         2  
  1         6  
7 1     1   1603 use Dancer2::Plugin;
  1         13624  
  1         6  
8              
9             has content_type => (
10             is => 'ro',
11             isa => Str,
12             from_config => sub { 'text/xml' },
13             );
14              
15             plugin_keywords 'ajax';
16              
17             sub ajax {
18 4     4 0 1612 my ( $plugin, $pattern, @rest ) = @_;
19              
20 4         11 my @default_methods = ( 'get', 'post' );
21              
22             # If the given pattern is an ArrayRef, we override the default methods
23 4 100       16 if( ref($pattern) eq "ARRAY" ) {
24 1         4 @default_methods = @$pattern;
25 1         3 $pattern = shift(@rest);
26             }
27              
28 4         7 my $code;
29 4 50       10 for my $e (@rest) { $code = $e if ( ref($e) eq 'CODE' ) }
  4         13  
30              
31             my $ajax_route = sub {
32              
33             # # must be an XMLHttpRequest
34 8 100   8   254016 if ( not $plugin->app->request->is_ajax ) {
35 2         405 $plugin->app->pass;
36             }
37              
38             # Default response content type is either what's defined in the
39             # plugin setting or text/xml
40 6 50       1671 $plugin->app->response->header('Content-Type')
41             or $plugin->app->response->content_type( $plugin->content_type );
42              
43             # disable layout
44 6         2099 my $layout = $plugin->app->config->{'layout'};
45 6         149 $plugin->app->config->{'layout'} = undef;
46 6         56 my $response = $code->(@_);
47 6         134 $plugin->app->config->{'layout'} = $layout;
48 6         49 return $response;
49 4         20 };
50              
51 4         9 foreach my $method ( @default_methods ) {
52 9         6126 $plugin->app->add_route(
53             method => $method,
54             regexp => $pattern,
55             code => $ajax_route,
56             );
57             }
58             }
59              
60             1;
61              
62             __END__