[Dancer-users] [RFC] Change in prefix / before functionality

David Precious davidp at preshweb.co.uk
Mon Mar 28 23:38:56 CEST 2011


On Mon, 2011-03-28 at 20:51 +0100, Simon Wistow wrote:
> I'd really like to be able to do something like this
> 
> --- >8 ---
> 
> package MyApp;
> 
> use MyApp::Secret;
> 
> prefix 'undef';
> 
> before sub {
>   # do something
> };
> 
> package MyApp::Secret;
> 
> prefix '/secret';
> 
> before sub {
> 	return unless auth && auth->is_admin;
> }
> 
> 1;
> 
> --- >8 ---
> 
> Rather than having to have the before sub in the main MyApp do all my 
> auth work (or conditionally load resources or whatever).
> 
> However at the moment *all* before subs get run no matter what the route 
> is

That's by design, but the before filter can always inplement whatever
logic it wants, e.g.:

before sub {
    if (request->{path} =~ m{^/secret} && !auth || !auth->is_admin) {
        redirect '/login';
    }
};


We could perhaps add the ability to pass options to 'before', e.g.:

before { path => m{^/secret} } => sub { ... };

(or reversed, before sub { ....} { path ... }; )

However, we'd be getting close to 'before' just being used as another
way to declare route handlers.

In fact, you could use a route for this, e.g.:

prefix '/secret';
any qr{.*} => sub {
    redirect '/login' if !auth || !auth->is_admin;
    pass;  # continue on to the next route which matches
};

get '/foo' => sub { "Foo!" };

... that should cause all requests for anything under that prefix to hit
that first route, which will either redirect to login, or pass(),
causing execution to continue on to the next route which matches the
request.

Cheers

Dave P


-- 
David Precious  ("bigpresh")
http://www.preshweb.co.uk/

   "Programming is like sex. One mistake and you have to support
   it for the rest of your life". (Michael Sinz)




More information about the Dancer-users mailing list