Skip to content

Commit

Permalink
merge arguments in subroutes by pushing
Browse files Browse the repository at this point in the history
  • Loading branch information
vti committed Dec 26, 2016
1 parent eb8bfc7 commit 5d5ebb5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
31 changes: 27 additions & 4 deletions lib/Routes/Tiny/Pattern.pm
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ sub new {
my $self = {};
bless $self, $class;

if (my $arguments = delete $params{'+arguments'}) {
$self->{arguments_push} = 1;
$params{arguments} = $arguments;
}

$self->{name} = $params{name};
$self->{defaults} = $params{defaults};
$self->{arguments} = $params{arguments};
Expand Down Expand Up @@ -72,10 +77,28 @@ sub match {
}
}

my $arguments = {
%{ $args{arguments} || {} },
%{ $self->arguments || {} }
};
my $arguments;
if ($self->{arguments_push}) {
%$arguments = %{ $self->arguments };

foreach my $key (keys %{ $args{arguments} || {} }) {
my $value = $args{arguments}->{$key};

if (exists $arguments->{$key}) {
$arguments->{$key} = [$arguments->{$key}] unless ref $arguments->{$key} eq 'ARRAY';
unshift @{ $arguments->{$key} }, ref $value eq 'ARRAY' ? @$value : $value;
}
else {
$arguments->{$key} = $value;
}
}
}
else {
$arguments = {
%{ $args{arguments} || {} },
%{ $self->arguments || {} }
};
}

my $match = $self->_build_match(
name => $self->name,
Expand Down
21 changes: 21 additions & 0 deletions t/subroutes.t
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,25 @@ subtest 'merges arguments' => sub {
};
};

subtest 'merges arguments pushing' => sub {
my $last = Routes::Tiny->new;
$last->add_route('/last/:id/', '+arguments' => {foo => 'bar3', bar => 'baz'});

my $second = Routes::Tiny->new;
$second->mount('/second/:parent_id/', $last, '+arguments' => {second => 'argument', foo => 'bar2'});

my $top = Routes::Tiny->new;
$top->mount('/top/:topic', $second, arguments => {top => 'argument', foo => 'bar'});

my $match = $top->match('/top/rainbows/second/5/last/7/');

is_deeply $match->arguments,
{
top => 'argument',
second => 'argument',
foo => ['bar', 'bar2', 'bar3'],
bar => 'baz',
};
};

done_testing;

0 comments on commit 5d5ebb5

Please sign in to comment.