如何在葡萄的一个街区中创建两条路线? [英] How to create two routes in one block in grape?
问题描述
我想在一个动作块中捕捉2条相似的路线.在Rails5中,我可以轻松地做到这一点.我首先声明:
I want to catch 2 similar route in one action block. In Rails5 I can do that easily. I first declare this:
get ':folder/:file' => 'get#index', :file => /.*/, :folder => /.*/
get ':file' => 'get#index', :file => /.*/
这使我可以捕获:folder
,就像在最后一个文件名末尾的a/b/c/d...
和:file
一样.第二个也允许我仅捕获文件名. 这两个路线都针对同一行动.
This allows me to catch :folder
as much as folder can be like a/b/c/d...
and :file
at end one last filename. Second one also allow me to only catch filenames. And both routes target to same action.
但是,在Grape中,因为它被声明为块而不是路由到方法定义,所以我必须写两次相同的块...
However, In Grape because it is declared as blocks rather than route to method definitions, I have to write same block twice...
有什么方法可以在一个路由参数中同时捕获/as/many/folder/and/file.ext
和/file.ext
吗?我尝试了可选参数,要求.他们都没有工作.
Is there any way to catch both /as/many/folder/and/file.ext
and just /file.ext
in one route parameter? I tried optional params, requirements. None of them worked.
我使用:folder/:file
(两次正则表达式)的原因是,我可以分别获取:folder
参数和:file
参数,而无需手动将其拆分.
The reason behind I use :folder/:file
(twice regexp) is i can grab :folder
param and :file
param separately without manually splitting them.
get ':folder/:file', requirements: { file: /.*/, folder: /.*/ } do
# params[:folder] and params[:file]
end
get ':file', requirements: { file: /.*/ } do
# params[:file]. [:folder is empty.]
end
^^我想使它们成为一条路线.如果文件夹存在(嵌套),则它将进入文件夹参数,否则文件夹将为零.
^^ I want to make them one single route. If folder exists (nested) then it will grab in folder param otherwise folder will be nil.
推荐答案
好.我通过尝试并参考refdocs找到了答案.
Ok. I've found the answer by trying and looking to refdocs.
get '(:folder/):file', requirements: { folder: /.*/, file: /.*/ } do
这按预期工作.
这篇关于如何在葡萄的一个街区中创建两条路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!