Make Gruntmaster::Page::Base::variants not need overriding
[gruntmaster-page.git] / lib / Gruntmaster / Page / Base.pm
1 package Gruntmaster::Page::Base;
2
3 use 5.014000;
4 use strict;
5 use warnings;
6
7 use File::Slurp qw/read_file/;
8 use HTML::Template::Compiled;
9
10 ##################################################
11
12 sub read_templates {
13 my $root = 'tmpl';
14 my $name = shift;
15
16 map { m/\.(.+)$/; $1 => scalar read_file $_ } <tmpl/$name.*>;
17 }
18
19 my %header_templates = read_templates 'header';
20 my %footer_templates = read_templates 'footer';
21
22 sub header{
23 my ($language, $title) = @_;
24 $header_templates{$language} =~ s/TITLE_GOES_HERE/$title/ger;
25 }
26
27 sub footer{
28 $footer_templates{$_[0]};
29 }
30
31 ##################################################
32
33 use POSIX ();
34 use Gruntmaster::Data ();
35 use List::Util ();
36 use LWP::UserAgent;
37
38 my $ua = LWP::UserAgent->new;
39 my %templates;
40
41 use Carp qw/cluck/;
42
43 sub import_to {
44 my ($self, $caller, $name, $title) = @_;
45
46 Gruntmaster::Data->export_to_level(1, $caller);
47 List::Util->export_to_level(1, $caller, qw/sum/);
48
49 no strict 'refs';
50 *{"${caller}::strftime"} = \&POSIX::strftime;
51 *{"${caller}::debug"} = sub {
52 local $Log::Log4perl::caller_depth = $Log::Log4perl::caller_depth + 1;
53 $_[0]->{'psgix.logger'}->({qw/level debug message/ => $_[1]})
54 };
55 *{"${caller}::reply"} = sub { [200, ['Content-Type' => 'text/plain', 'Cache-Control' => 'no-cache'], [ @_ ] ] };
56 *{"${caller}::purge"} = sub {
57 return unless $ENV{PURGE_HOST};
58 my $req = HTTP::Request->new(PURGE => "http://$ENV{PURGE_HOST}$_[0]");
59 $ua->request($req)
60 };
61
62 if ($name) {
63 $templates{$caller} = { read_templates $name };
64 $templates{$caller}{$_} = header ($_, $title) . $templates{$caller}{$_} for keys $templates{$caller};
65 $templates{$caller}{$_} .= footer $_ for keys $templates{$caller};
66 }
67 }
68
69 sub import {
70 return unless $_[0] eq __PACKAGE__;
71 splice @_, 1, 0, scalar caller;
72 goto &import_to
73 }
74
75 ##################################################
76
77 sub generate{
78 my ($self, $lang, @args) = @_;
79
80 my $htc = HTML::Template::Compiled->new(scalarref => \$templates{$self}{$lang}, default_escape => 'HTML',);
81 $self->_generate($htc, $lang, @args);
82 my $out = $htc->output;
83 utf8::downgrade($out);
84 my $vary = 'Accept-Language, ' . $self->vary;
85 [200, ['Content-Type' => 'text/html', 'Content-Language' => $_[1], 'Vary' => $vary, 'X-Forever' => 1, 'Cache-Control' => 'max-age=' . $self->max_age], [ $out ] ]
86 }
87
88 sub _generate {}
89
90 sub vary { '' }
91
92 sub max_age { 60 }
93
94 sub variants {
95 return [] unless exists $templates{$_[0]};
96 [ map { [ $_, 1, 'text/html', undef, undef, $_, undef ]} keys $templates{$_[0]} ]
97 }
98
99 1
This page took 0.028097 seconds and 4 git commands to generate.