Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Mojo::Promise handling to the eval command #1306

Merged
merged 2 commits into from
Dec 31, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions lib/Mojolicious/Command/eval.pm
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package Mojolicious::Command::eval;
use Mojo::Base 'Mojolicious::Command';

use Mojo::Promise;
use Mojo::Util 'getopt';

has description => 'Run code against application';
Expand All @@ -16,7 +17,12 @@ 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 $@;
my $err;
Mojo::Promise->resolve($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 @@ -48,7 +54,9 @@ Mojolicious::Command::eval - Eval command

=head1 DESCRIPTION

L<Mojolicious::Command::eval> runs code against applications.
L<Mojolicious::Command::eval> runs code against applications. If the result is
a promise (then-able), it will wait until the promise is fulfilled or rejected 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