Monday 17 June 2013

Dancer2: changing path_info in a before hook

Dancer2 is a great piece of software, easy to use and smart. But it's still evolving and working with it could be a little rude. Easy tasks could take a lot of time (and patience) with no possibility to straight google your solution out of few keywords.

I wanted to preprocess the calls my Dancer2 site receives in a before hook and change them to have a cleaner dispatching. For example I wanted to receive
/foo/bar
keep /foo for me and make the call processed by
get '/bar'  => sub
(i'll tell you why another day, but you can easly guess).

It's a standard task and this page  has an example about exactly what i want. An example that... well... doesn't work.

I admit I went a bit on rage, howling against all the Dancer2 Gods when I understood that something was wrong but when the angry moment finished I started digging in the documentation finding this issue.

"Argh!" said the blood thirsy Wotan worshipper inside me "They knew it. They fixed it. And It's still not working!"

Probability that the fix wasn't in the CPAN package I downloaded was high, as I said, Dancer2 is still evolving, it' version is still starting with a double 0 and we're all beta-testers, but the time of the pull request said otherwise so I went on digging.

We're lucky people because we live in a test-driven world. Let us see how the test for this fix is written...:

hook before => sub { 
my $context = shift;
return if $context->request->path eq '/default';
$context->response( forward('/default') );
$context->response->halt;
}; 


...and that's the way to do it! I hope someone will find this post before they have to start the voyage I did to find the solution. This will keep the Wotan worshipper calm a bit more...



No comments:

Post a Comment