| 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 | use strict; | ||
| 6 | use warnings; | ||
| 7 | |||
| 8 | use Dancer ':syntax'; | ||
| 9 | use Dancer::Exception ':all'; | ||
| 10 | use Dancer::Plugin; | ||
| 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 | my ($pattern, @rest) = @_; | ||
| 22 | |||
| 23 | my $code; | ||
| 24 | for my $e (@rest) { $code = $e if (ref($e) eq 'CODE') } | ||
| 25 | |||
| 26 | my $ajax_route = sub { | ||
| 27 | # must be an XMLHttpRequest | ||
| 28 | if (not request->is_ajax) { | ||
| 29 | pass and return 0; | ||
| 30 | } | ||
| 31 | |||
| 32 | # disable layout | ||
| 33 | my $layout = setting('layout'); | ||
| 34 | setting('layout' => undef); | ||
| 35 | my $response = try { | ||
| 36 | $code->(); | ||
| 37 | } catch { | ||
| 38 | my $e = $_; | ||
| 39 | setting('layout' => $layout); | ||
| 40 | die $e; | ||
| 41 | }; | ||
| 42 | setting('layout' => $layout); | ||
| 43 | return $response; | ||
| 44 | }; | ||
| 45 | |||
| 46 | # rebuild the @rest array with the compiled route handler | ||
| 47 | my @compiled_rest; | ||
| 48 | for my $e (@rest) { | ||
| 49 | if (ref($e) eq 'CODE') { | ||
| 50 | push @compiled_rest, {ajax => 1}, $ajax_route; | ||
| 51 | } | ||
| 52 | else { | ||
| 53 | push @compiled_rest, {ajax => 1}, $e; | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | any ['get', 'post'] => $pattern, @compiled_rest; | ||
| 58 | } | ||
| 59 | |||
| 60 | register_plugin; | ||
| 61 | 1; | ||
| 62 | |||
| 63 | __END__ |