Last active
December 10, 2015 00:29
-
-
Save kraih/4351674 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
use Mojolicious::Lite; | |
use Mojolicious::Lite::MyKeywords; | |
get_post '/' => sub { | |
render text => 'Hello keywords!'; | |
}; | |
app->start; |
This file contains hidden or 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::Lite::MyKeywords; | |
use Mojo::Base -base; | |
use Mojo::Util 'monkey_patch'; | |
sub import { | |
my $caller = caller; | |
# Export "get_post" keyword (reuse "any" keyword to make "under" work) | |
monkey_patch $caller, 'get_post', sub { | |
return $caller->can('any')->([qw(GET POST)] => @_); | |
}; | |
# Add magical "current_controller" helper for "render" keyword | |
$caller->app->hook( | |
around_dispatch => sub { | |
my ($next, $c) = @_; | |
local $c->app->renderer->helpers->{current_controller} = sub {$c}; | |
$next->(); | |
} | |
); | |
# Export "render" keyword (does not work for delayed rendering) | |
monkey_patch $caller, 'render', sub { | |
return $caller->app->current_controller->render(@_); | |
}; | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In case you're wondering why we don't do this in Mojolicious. The following example application would not work, due to context switching to the event loop, before using the
render
keyword.This kind of DSL requires global state, which gets in the way of concurrency.