Skip to content

Commit

Permalink
match routes a little more efficiently
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed May 6, 2013
1 parent 8e90fbb commit 4ecb40f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 18 deletions.
18 changes: 7 additions & 11 deletions lib/Mojolicious/Routes/Match.pm
Expand Up @@ -7,24 +7,23 @@ has stack => sub { [] };

sub new {
my $self = shift->SUPER::new;
$self->{method} = uc shift;
$self->{path} = shift;
$self->{websocket} = shift;
$self->{method} = uc shift;
$self->{$_} = shift for qw(path websocket);
return $self;
}

sub match {
my ($self, $r, $c) = @_;
$self->root($r) unless $self->root;

# Pattern
$self->root($r) unless $self->root;
my $path = $self->{path};
my $pattern = $r->pattern;
return unless my $captures = $pattern->shape_match(\$path, $r->is_endpoint);
$self->{path} = $path;
local $self->{path} = $path;
$captures = {%{$self->captures}, %$captures};

# Method
# Method (HEAD will be treated as GET)
if (my $methods = $r->via) {
my $method = $self->{method} eq 'HEAD' ? 'GET' : $self->{method};
return unless grep { $_ eq $method } @$methods;
Expand All @@ -50,17 +49,15 @@ sub match {
$empty = 1;
}

# Update stack
# Endpoint
$self->captures($captures);
my $endpoint = $r->is_endpoint;
if ($r->inline || ($endpoint && $empty)) {
push @{$self->stack}, {%$captures};
delete $captures->{$_} for qw(app cb);
return $self->endpoint($r) if $endpoint && $empty;
}

# Endpoint
return $self->endpoint($r) if $endpoint && $empty;

# Match children
my $snapshot = [@{$self->stack}];
for my $child (@{$r->children}) {
Expand All @@ -70,7 +67,6 @@ sub match {
return if $self->endpoint;

# Reset
$self->{path} = $path;
if ($r->parent) { $self->captures($captures)->stack([@$snapshot]) }
else { $self->captures({})->stack([]) }
}
Expand Down
10 changes: 3 additions & 7 deletions lib/Mojolicious/Routes/Pattern.pm
Expand Up @@ -80,7 +80,7 @@ sub shape_match {

# Match
return undef unless my @captures = $$pathref =~ $regex;
$$pathref =~ s/($regex)//;
$$pathref =~ s/$regex//;

# Merge captures
my $result = {%{$self->defaults}};
Expand All @@ -103,19 +103,16 @@ sub _compile {
my $self = shift;

my $block = my $regex = '';
my $constraints = $self->constraints;
my $optional = 1;
my $constraints = $self->constraints;
my $defaults = $self->defaults;
for my $token (reverse @{$self->tree}) {
my $op = $token->[0];
my $compiled = '';

# Slash
if ($op eq 'slash') {

# Full block
$block = $optional ? "(?:/$block)?" : "/$block";
$regex = "$block$regex";
$regex = ($optional ? "(?:/$block)?" : "/$block") . $regex;
$block = '';
next;
}
Expand Down Expand Up @@ -155,7 +152,6 @@ sub _compile {
# Not rooted with a slash
$regex = "$block$regex" if $block;

# Compile
return $self->regex(qr/^$regex/s)->regex;
}

Expand Down

0 comments on commit 4ecb40f

Please sign in to comment.