Skip to content

Commit

Permalink
improved Mojo::Template exception handling (closes #321)
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Apr 20, 2012
1 parent 4c5e5a9 commit 86c6ec0
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 11 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,6 +1,7 @@
This file documents the revision history for Perl extension Mojolicious.

2.86 2012-04-20
- Improved Mojo::Template exception handling.
- Improved documentation.

2.85 2012-04-19
Expand Down
19 changes: 9 additions & 10 deletions lib/Mojo/Template.pm
Expand Up @@ -151,11 +151,9 @@ sub interpret {
# Interpret
return unless my $compiled = $self->compiled;
my $output = eval { $compiled->(@_) };
$output
= Mojo::Exception->new($@, [$self->template], $self->name)->verbose(1)
if $@;

return $output;
return $@
? Mojo::Exception->new($@, [$self->template], $self->name)->verbose(1)
: $output;
}

# "I am so smart! I am so smart! S-M-R-T! I mean S-M-A-R-T..."
Expand Down Expand Up @@ -313,22 +311,23 @@ sub render_file {
while ($file->sysread(my $buffer, CHUNK_SIZE, 0)) { $tmpl .= $buffer }

# Decode and render
$tmpl = decode $self->encoding, $tmpl if $self->encoding;
if (my $encoding = $self->encoding) {
croak qq/Template "$path" has invalid encoding./
unless defined($tmpl = decode $encoding, $tmpl);
}
return $self->render($tmpl, @_);
}

sub render_file_to_file {
my ($self, $spath, $tpath) = (shift, shift, shift);
my $output = $self->render_file($spath, @_);
return $output if ref $output;
return $self->_write_file($tpath, $output);
return ref $output ? $output : $self->_write_file($tpath, $output);
}

sub render_to_file {
my ($self, $tmpl, $path) = (shift, shift, shift);
my $output = $self->render($tmpl, @_);
return $output if ref $output;
return $self->_write_file($path, $output);
return ref $output ? $output : $self->_write_file($path, $output);
}

sub _trim {
Expand Down
10 changes: 9 additions & 1 deletion t/mojo/template.t
Expand Up @@ -17,7 +17,7 @@ use Mojo::Base -strict;

use utf8;

use Test::More tests => 197;
use Test::More tests => 199;

# "When I held that gun in my hand, I felt a surge of power...
# like God must feel when he's holding a gun."
Expand Down Expand Up @@ -1064,3 +1064,11 @@ is $output->lines_after->[0]->[1], '☃', 'right line';
is utf8::is_utf8($output->lines_before->[0]->[1]), 1, 'context has utf8 flag';
is utf8::is_utf8($output->line->[1]), 1, 'context has utf8 flag';
is utf8::is_utf8($output->lines_after->[0]->[1]), 1, 'context has utf8 flag';

# Different encodings
$mt = Mojo::Template->new(encoding => 'ISO-8859-1');
$file = catfile $dir, 'test3.mt';
is $mt->render_to_file('ü', $file), undef, 'file rendered';
$mt = Mojo::Template->new(encoding => 'UTF-8');
eval { $mt->render_file($file) };
like $@, qr/invalid encoding/, 'right error';

0 comments on commit 86c6ec0

Please sign in to comment.