Skip to content

Instantly share code, notes, and snippets.

@xsawyerx
Last active January 2, 2016 00:21
Show Gist options
  • Save xsawyerx/e0095c87e0da26196f61 to your computer and use it in GitHub Desktop.
Save xsawyerx/e0095c87e0da26196f61 to your computer and use it in GitHub Desktop.
uri_for() with parameters
package MyApp;
use Carp;
use Dancer2;
my %routes;
sub uri_for_it {
my ( $name, $vars ) = @_;
my $route = $routes{$name};
my $route_path = $route->spec_route;
my $route_params = $route->_params;
# double check we only have tokens
if ( $route->regexp =~ /\(\?\#(?:mega)?splat\)/ ) {
carp 'splat variables are not supported';
return;
}
foreach my $param ( @{$route_params} ) {
$route_path =~ s{:$param}{$vars->{$param}};
}
return $route_path;
}
sub named_route {
my ( $name, @routes ) = @_;
my @filtered_routes = grep +(
ref $_ eq 'Dancer2::Core::Route' && $_->method ne 'head'
), @routes;
@filtered_routes == 1
or croak("Multiple routes defined for $name");
my $route = $filtered_routes[0];
$routes{$name} = $route;
}
named_route product => get '/:action/:id/' => sub {"OK\n"};
uri_for_it( product => { id => 5, action => 'view' } ); # /view/5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment