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