WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Commit 5bea8b7

Browse files
committed
add generic id stash value for multi-part IDs
This obsoletes entirely the Yancy::Controller::Yancy::API controller, as that was about the only thing it did differently. Since I'm in the middle of a total revamp of the editor, I'll remove that later.
1 parent bd2d2b5 commit 5bea8b7

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

lib/Yancy/Controller/Yancy.pm

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,10 +238,23 @@ Get the ID for the currently-requested item, if available, or C<undef>.
238238
sub item_id {
239239
my ( $self ) = @_;
240240
my $id_field = $self->schema->id_field;
241+
# First, allow a generic 'id' stash/route value to define all parts of the
242+
# item's ID. This allows us to accept multiple schemas in the same
243+
# route definition.
244+
if (my $id_path = $self->stash('id')) {
245+
if ( ref $id_field eq 'ARRAY' ) {
246+
my @id_parts = split m{/}, $id_path;
247+
return { map { $id_field->[$_] => $id_parts[$_] } 0..$#$id_field };
248+
}
249+
return $id_path;
250+
}
251+
# Otherwise, the ID must be defined as separate fields
241252
if ( ref $id_field eq 'ARRAY' ) {
253+
# Multi-part keys are hash references
242254
my $id = { map { $_ => $self->stash( $_ ) } grep defined $self->stash( $_ ), @$id_field };
243255
return keys %$id == @$id_field ? $id : undef;
244256
}
257+
# Must be a single key, a simple scalar
245258
return $self->stash( $id_field ) // undef;
246259
}
247260

t/controller/yancy.t

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,9 @@ $r->get( '/blog/usersub/:userid/:page', {
165165
page => 1,
166166
} )
167167
->to( 'yancy#list' => schema => 'blog', template => 'blog_list' );
168+
$r->get( '/api/:schema/*id' )
169+
->to( 'yancy#get' => format => 'json' )
170+
->name( 'api.get' );
168171

169172
subtest 'list' => sub {
170173
$t->get_ok( '/blog/page' )
@@ -300,6 +303,11 @@ subtest 'get' => sub {
300303
->status_is( 404 );
301304
};
302305

306+
subtest 'multiple ID parts' => sub {
307+
$t->get_ok( "/api/blog/$items{blog}[0]{id}", { Accept => 'application/json' } )
308+
->json_is( $items{blog}[0] )
309+
};
310+
303311
subtest 'subclassing/extending' => sub {
304312
$t->get_ok( "/extend/$items{blog}[0]{id}/first-post" )
305313
->text_is( 'article:nth-child(1) h1', 'Extended' )

0 commit comments

Comments
 (0)