File Coverage

blib/lib/Dancer2/Plugin/SendAs.pm
Criterion Covered Total %
statement 31 31 100.0
branch 2 2 100.0
condition n/a
subroutine 8 8 100.0
pod n/a
total 41 41 100.0


line stmt bran cond sub pod time code
1             package Dancer2::Plugin::SendAs;
2             # ABSTRACT: Dancer2 plugin to send data as specific content type
3              
4 1     1   470660 use strict;
  1         3  
  1         24  
5 1     1   5 use warnings;
  1         1  
  1         24  
6              
7 1     1   732 use Dancer2::Plugin;
  1         2276  
  1         7  
8              
9 1     1   2007 use Class::Load 'try_load_class';
  1         1  
  1         53  
10 1     1   5 use Encode;
  1         2  
  1         91  
11 1     1   5 use List::Util 'first';
  1         2  
  1         273  
12              
13             our $VERSION = '0.001'; # VERSION
14              
15             register send_as => sub {
16 2     2   179951 my ( $dsl, $type, $data ) = @_;
17              
18             # allow lower cased serializer names
19 3     3   593 my $serializer_class = first { try_load_class($_) }
20 2         12 map { "Dancer2::Serializer::$_" }
  4         19  
21             ( uc $type, $type );
22              
23 2         5747 my %options = ();
24 2         4 my $content;
25              
26 2 100       9 if ( $serializer_class ) {
27 1         5 my $serializer = $serializer_class->new;
28 1         3059 $content = $serializer->serialize( $data );
29 1         415 $options{content_type} = $serializer->content_type;
30             }
31             else {
32             # send as HTML
33             # TODO use content type of app
34 1         7 $content = Encode::encode( 'UTF-8', $data );
35 1         54 $options{content_type} = 'text/html; charset=UTF-8';
36             }
37              
38 2         17 $dsl->app->send_file( \$content, %options );
39             }, { prototype => '$@' };
40              
41             register_plugin;
42              
43             1;
44              
45             __END__