Skip to content

Commit

Permalink
eval command is Mojo::Promise aware
Browse files Browse the repository at this point in the history
  • Loading branch information
jberger committed Dec 29, 2018
1 parent fb702a7 commit 33cfa31
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/Mojolicious/Command/eval.pm
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package Mojolicious::Command::eval;
use Mojo::Base 'Mojolicious::Command';

use Mojo::Util 'getopt';
use Scalar::Util 'blessed';

has description => 'Run code against application';
has usage => sub { shift->extract_usage };
Expand All @@ -16,7 +17,13 @@ sub run {
my $app = $self->app;
no warnings;
my $result = eval "package main; sub app; local *app = sub { \$app }; $code";
return $@ ? die $@ : $result unless defined $result && ($v1 || $v2);
die $@ if $@;
if (blessed $result && $result->isa('Mojo::Promise')) {
my $err;
$result->then(sub { $result = shift }, sub { $err = shift })->wait;
die $err if $err;
}
return $result unless defined $result && ($v1 || $v2);
$v2 ? print($app->dumper($result)) : say $result;
}

Expand Down Expand Up @@ -49,6 +56,7 @@ Mojolicious::Command::eval - Eval command
=head1 DESCRIPTION
L<Mojolicious::Command::eval> runs code against applications.
If the result is a L<Mojo::Promise>, it will wait until the promise is completed and the result is returned.
This is a core command, that means it is always enabled and its code a good
example for learning to build new commands, you're welcome to fork it.
Expand Down
9 changes: 9 additions & 0 deletions t/mojolicious/commands.t
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,15 @@ $buffer = '';
$eval->run('-v', 'app->controller_class');
}
like $buffer, qr/Mojolicious::Controller/, 'right output';
$buffer = '';
{
open my $handle, '>', \$buffer;
local *STDOUT = $handle;
$eval->run('-v', 'Mojo::Promise->new->resolve("Zoidberg")');
}
like $buffer, qr/Zoidberg/, 'right output';
eval { $eval->run('-v', 'Mojo::Promise->new->reject("DOOM")') };
like $@, qr/DOOM/, 'right output';

# generate
require Mojolicious::Command::Author::generate;
Expand Down

0 comments on commit 33cfa31

Please sign in to comment.