Skip to content

Instantly share code, notes, and snippets.

@Akron
Created November 18, 2011 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akron/1377904 to your computer and use it in GitHub Desktop.
Save Akron/1377904 to your computer and use it in GitHub Desktop.
Filter Plugin
package Mojolicious::Plugin::Filter;
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->(@_);
};
# New filter object
Mojolicious::Plugin::Filter::Instance->new(
subscribers => [ @{$filters{ $name }}, $cb ],
param => \@_,
c => $c
)->next;
}
);
# Chain helper
$mojo->helper(
'chain' => sub {
my ($c, $name, $cb) = @_;
# Maybe first subscription
$filters{$name} //= [];
# Push callback
push (@{ $filters{$name} }, $cb);
}
);
};
package Mojolicious::Plugin::Filter::Instance;
use Mojo::Base -base;
# Next method
sub next {
my $self = shift;
my $next = shift(@{$self->{subscribers}});
# No next nothing
return unless $next;
# Subscriber callbacks
if (@{$self->{subscribers}} >= 1) {
$next->($self, $self->{c}, @{$self->{param}});
}
# Final callback
else {
$next->($self->{c}, @{$self->{param}});
};
};
__END__
#!/usr/bin/env perl
use Mojolicious::Lite;
plugin 'Filter';
app->chain(
'on_welcome' => sub {
my ($f, $c, $message) = @_;
$$message =~ s/e/a/g;
$f->next;
});
app->chain(
'on_welcome' => sub {
my ($f, $c, $message) = @_;
$$message = lc($$message);
$f->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