File Coverage

blib/lib/Plack/App/Directory/Xslate.pm
Criterion Covered Total %
statement 9 9 100.0
branch n/a
condition n/a
subroutine 3 3 100.0
pod n/a
total 12 12 100.0


line stmt bran cond sub pod time code
1             package Plack::App::Directory::Xslate;
2 1     1   27007 use strict;
  1         2  
  1         43  
3 1     1   6 use warnings;
  1         3  
  1         53  
4              
5             our $VERSION = '0.07';
6              
7 1     1   1217 use parent qw(Plack::App::Directory);
  1         390  
  1         6  
8              
9             use Text::Xslate;
10             use Encode ();
11             use File::Spec;
12              
13             use Plack ();
14             use Plack::App::File ();
15             use Plack::Util ();
16             use Plack::Util::Accessor qw(xslate_opt xslate_path xslate_param);
17              
18             sub new {
19             my $class = shift;
20             my $self = $class->SUPER::new(@_);
21              
22             $self->xslate_opt->{path} = $self->root;
23             $self->{xslate} = Text::Xslate->new($self->xslate_opt);
24             $self->{encoder} = Encode::find_encoding('utf-8');
25             $self->xslate_param(+{}) unless $self->xslate_param;
26              
27             $self->xslate_path(sub {}) unless $self->xslate_path;
28             if (ref $self->xslate_path eq 'Regexp') {
29             my $re = $self->xslate_path;
30             $self->xslate_path(sub { $_ =~ $re });
31             }
32              
33             return $self;
34             }
35              
36             sub serve_path {
37             my ($self, $env, $path, $fullpath) = @_;
38              
39             if (-f $path && $self->is_xslate_path($path)) {
40             return $self->serve_xslate($env, $path, $fullpath);
41             }
42             else {
43             return $self->SUPER::serve_path($env, $path, $fullpath);
44             }
45             }
46              
47             sub is_xslate_path {
48             my ($self, $path) = @_;
49              
50             local $_ = $path;
51             return $self->xslate_path->($path);
52             }
53              
54             sub serve_xslate {
55             my ($self, $env, $path, $fullpath) = @_;
56              
57             my $tmpl_path = File::Spec->abs2rel($path, $self->root);
58             my $content = $self->{encoder}->encode(
59             $self->{xslate}->render($tmpl_path, $self->xslate_param)
60             );
61             return [
62             200,
63             [
64             'Content-Type' => 'text/html',
65             'Content-Length' => Plack::Util::content_length($content),
66             ],
67             [$content]
68             ];
69             }
70              
71             1;
72             __END__