| 1 | package Terse::View::Static::Memory; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use base 'Terse::View::Static'; | ||
| 7 | |||
| 8 | sub build_view { | ||
| 9 | my ($self) = @_; | ||
| 10 | $self->SUPER::build_view(); | ||
| 11 | $self->memory_cached_templates = $self->_read_directory_content($self->dir) ; | ||
| 12 | return $self; | ||
| 13 | } | ||
| 14 | |||
| 15 | sub _read_directory_content { | ||
| 16 | my ($self, $dir) = @_; | ||
| 17 | my $allowed = $self->allowed; | ||
| 18 | return { map { | ||
| 19 | ( $_ => $self->_read_file("$dir/$_") ); | ||
| 20 | } $self->_recurse_directory("${dir}") }; | ||
| 21 | } | ||
| 22 | |||
| 23 | sub _recurse_directory { | ||
| 24 | my ($self, $dir, $path, @files) = @_; | ||
| 25 | return () unless -d $dir; | ||
| 26 | opendir my $d, $dir or $self->logError("Cannot read controller directory: $!", 500, 1); | ||
| 27 | my $allowed = $self->allowed; | ||
| 28 | for (readdir $d) { | ||
| 29 | next if $_ =~ m/^\./; | ||
| 30 | if (-d "$dir/$_") { | ||
| 31 | push @files, $self->_recurse_directory("$dir/$_", $path ? "$path/$_" : $_); | ||
| 32 | } elsif ($_ =~ m/\.($allowed)$/) { | ||
| 33 | push @files, $path ? "$path/$_" : $_; | ||
| 34 | } | ||
| 35 | } | ||
| 36 | closedir $d; | ||
| 37 | return @files; | ||
| 38 | } | ||
| 39 | |||
| 40 | sub render { | ||
| 41 | my ($self, $t, $data) = @_; | ||
| 42 | my $template = $t->captured->[0] || $data->template || $t->template || $t->req; | ||
| 43 | $template = 'html/' . $template . '.html' if ($template !~ m/\.[^\.]+$/); | ||
| 44 | my $allowed = $self->allowed; | ||
| 45 | my ($mime) = $template =~ m/($allowed)$/; | ||
| 46 | return $t->logError('Invalid file mime type for file: ' . $template, 500, 1) unless $mime && $self->mime->$mime; | ||
| 47 | return $t->logError('File not found: ' . $template, 500, 1) unless $self->memory_cached_resourcess->{$template}; | ||
| 48 | return ($self->mime->$mime, $self->memory_cached_resources->{$template}); | ||
| 49 | } | ||
| 50 | |||
| 51 | 1; | ||
| 52 | |||
| 53 | =head1 NAME | ||
| 54 | |||
| 55 | Terse::View::Static::Memory - Serve static resources in memory view | ||
| 56 | |||
| 57 | =cut | ||
| 58 | |||
| 59 | =head1 VERSION | ||
| 60 | |||
| 61 | Version 0.13 | ||
| 62 | |||
| 63 | =cut | ||
| 64 | |||
| 65 | =head1 SYNOPSIS | ||
| 66 | |||
| 67 | package MyApp::View::Static; | ||
| 68 | |||
| 69 | use base 'Terse::View::Static::Memory'; | ||
| 70 | |||
| 71 | 1; | ||
| 72 | |||
| 73 | =cut | ||
| 74 | |||
| 75 | =head1 LICENSE AND COPYRIGHT | ||
| 76 | |||
| 77 | L<Terse::Static>. | ||
| 78 | |||
| 79 | =cut |