Skip to content

Commit

Permalink
added remaining attribute to Mojo::IOLoop::Delay
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Feb 22, 2014
1 parent 47d6eb2 commit 87ae27b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
3 changes: 2 additions & 1 deletion Changes
@@ -1,5 +1,6 @@

4.84 2014-02-21
4.84 2014-02-22
- Added remaining attribute to Mojo::IOLoop::Delay.

4.83 2014-02-19
- Improved Mojo::JSON to handle encoding errors more gracefully.
Expand Down
15 changes: 11 additions & 4 deletions lib/Mojo/IOLoop/Delay.pm
Expand Up @@ -3,7 +3,8 @@ use Mojo::Base 'Mojo::EventEmitter';

use Mojo::IOLoop;

has ioloop => sub { Mojo::IOLoop->singleton };
has ioloop => sub { Mojo::IOLoop->singleton };
has remaining => sub { [] };

sub begin {
my ($self, $ignore) = @_;
Expand All @@ -13,8 +14,7 @@ sub begin {
}

sub steps {
my $self = shift;
$self->{steps} = [@_];
my $self = shift->remaining([@_]);
$self->ioloop->timer(0 => $self->begin);
return $self;
}
Expand All @@ -41,7 +41,7 @@ sub _step {
my @args = map {@$_} @{delete $self->{args}};

$self->{counter} = 0;
if (my $cb = shift @{$self->{steps} ||= []}) {
if (my $cb = shift @{$self->remaining}) {
eval { $self->$cb(@args); 1 } or return $self->emit(error => $@)->{fail}++;
}

Expand Down Expand Up @@ -143,6 +143,13 @@ L<Mojo::IOLoop::Delay> implements the following attributes.
Event loop object to control, defaults to the global L<Mojo::IOLoop>
singleton.
=head2 remaining
my $remaining = $delay->remaining;
$delay = $delay->remaining([sub {...}]);
Remaining L</"steps"> in chain.
=head1 METHODS
L<Mojo::IOLoop::Delay> inherits all methods from L<Mojo::EventEmitter> and
Expand Down
24 changes: 24 additions & 0 deletions t/mojo/delay.t
Expand Up @@ -163,6 +163,30 @@ is_deeply [$delay->wait], [2, 3, 2, 1, 4, 5, 6, 23], 'right return values';
is $finished, 1, 'finish event has been emitted once';
is_deeply $result, [1, 2, 3, 2, 3, 2, 1, 4, 5, 6, 23], 'right results';

# Dynamic step
my $double = sub {
my ($delay, $num) = @_;
my $end = $delay->begin(0);
Mojo::IOLoop->timer(0 => sub { $end->($num * 2) });
};
$result = undef;
$delay = Mojo::IOLoop::Delay->new->steps(
sub {
my $delay = shift;
my $end = $delay->begin(0);
Mojo::IOLoop->timer(0 => sub { $end->(9) });
unshift @{$delay->remaining}, $double;
},
sub {
my ($delay, $num) = @_;
$result = $num;
}
);
is scalar @{$delay->remaining}, 2, 'two steps remaining';
is_deeply [$delay->wait], [18], 'right return values';
is scalar @{$delay->remaining}, 0, 'no steps remaining';
is $result, 18, 'right result';

# Exception in first step
my $failed;
($finished, $result) = ();
Expand Down

0 comments on commit 87ae27b

Please sign in to comment.