MechanicalTurk/Template/PerlTemplate.pm untested

filter: Statementstmt 0.0% 0 / 50 Branchbran 0.0% 0 / 6 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 69 CC 4 SCAR 15.9
CC
4
Cov
0%
__compileSub__
12.0
merge
6.0
compileSource
2.0
CRAP 4.9
1 package Net::Amazon::MechanicalTurk::Template::PerlTemplate;
2 use strict;
3 use warnings;
4 use Carp;
5 use IO::File;
6 use IO::String;
7 use Net::Amazon::MechanicalTurk::Template;
8  
9 our $VERSION = '1.00';
10  
11 our @ISA = qw{ Net::Amazon::MechanicalTurk::Template };
12  
13 Net::Amazon::MechanicalTurk::Template::PerlTemplate->attributes(qw{
14 compiledSub
15 });
16  
17 sub compileSource {
18 my ($self, $text) = @_;
19
20 # Wrap the code in an anonymouse sub, so it only has to be eval'd once.
21 my $perlSource =
22 "return sub {\n" .
23 " my \$out = shift;\n" .
24 " my \%params = \%{\$_[0]};\n" .
25 $text . "\n" .
26 "}\n";
27  
28 $self->compiledSub(Net::Amazon::MechanicalTurk::Template::PerlTemplate::CompiledNameSpace::__compileSub__(
29 $perlSource,
30 $self->templateFile
31 ));
32 $self->compiled(1);
33 }
34  
35 sub merge {
36 my ($self, $params) = @_;
37 my $out = IO::String->new;
38 my $oldFh = select($out);
39 eval {
40 $self->compiledSub->($out, $params);
41 };
42 if ($@) {
43 my $error = $@;
44 select($oldFh);
45 Carp::croak("Error executing perl template " . $self->templateFile . " - $error.");
46 }
47 select($oldFh);
48 return ${$out->string_ref};
49 }
50  
51 package Net::Amazon::MechanicalTurk::Template::PerlTemplate::CompiledNameSpace;
52  
53 our $VERSION = '1.00';
54  
55 # provides a package to be used for evaluating code.
56 # A perl template may declare subs. If they are not qualified they will end up
57 # in here.
58 #
59 # WARNING:
60 # If a user compiles more than 1 template where more than 1 template has
61 # has a common subroutine name, then the last compiled template will be the
62 # one providing the implementation of the sub, for all templates.
63 #
64  
65 sub __compileSub__ {
66 # Use funky variable names to avoid clashing with template variables.
67 my $__perlSource__ = shift;
68 my $__perlSourceFile__ = shift;
69 no warnings;
70 my $__perlSub__ = eval $__perlSource__;
71 if ($@) {
72 Carp::croak("Couldn't compile perl source from $__perlSourceFile__ - $@.");
73 }
74 if (!UNIVERSAL::isa($__perlSub__, "CODE")) {
75 Carp::croak("Couldn't find compiled code in perl source $__perlSourceFile__.");
76 }
77 return $__perlSub__;
78 }
79  
80 return 1;