Created
November 18, 2011 22:23
-
-
Save Akron/1377960 to your computer and use it in GitHub Desktop.
Filter Plugin 2 - with Closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Mojolicious::Plugin::Filter2; | |
use Mojo::Base 'Mojolicious::Plugin'; | |
# Register plugin | |
sub register { | |
my ($plugin, $mojo) = @_; | |
my %filters; | |
# Filter helper | |
$mojo->helper( | |
'filter' => sub { | |
my $c = shift; | |
my $name = shift; | |
my $cb = pop; | |
# No subscribers | |
unless (exists $filters{$name}) { | |
return $cb->(@_); | |
}; | |
{ | |
my @subscribers = (@{$filters{ $name }}, $cb); | |
my @param = @_; | |
my $closure; | |
$closure = sub { | |
my $next = shift(@subscribers); | |
return unless $next; | |
# Subscriber callbacks | |
if (@subscribers >= 1) { | |
$next->($closure, $c, @param); | |
} | |
# Final callback | |
else { | |
$next->($c, @param); | |
}; | |
}; | |
$closure->(); | |
}; | |
} | |
); | |
# Chain helper | |
$mojo->helper( | |
'chain' => sub { | |
my ($c, $name, $cb) = @_; | |
# Maybe first subscription | |
$filters{$name} //= []; | |
# Push callback | |
push (@{ $filters{$name} }, $cb); | |
} | |
); | |
}; | |
1; | |
__END__ | |
#!/usr/bin/env perl | |
use Mojolicious::Lite; | |
plugin 'Filter2'; | |
app->chain( | |
'on_welcome' => sub { | |
my ($next, $c, $message) = @_; | |
$$message =~ s/e/a/g; | |
$next->(); | |
}); | |
app->chain( | |
'on_welcome' => sub { | |
my ($f, $c, $message) = @_; | |
$$message = lc($$message); | |
$next->(); | |
}); | |
get '/' => sub { | |
my $c = shift; | |
my $message = 'Hello World'; | |
$c->filter( | |
'on_welcome' => | |
\$message => | |
sub { | |
return $c->render_text($message); | |
}); | |
}; | |
app->start; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment