How to create two routes in one block in grape?

与世无争的帅哥 提交于 2019-12-19 11:30:06

问题


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 => /.*/

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.

However, In Grape because it is declared as blocks rather than route to method definitions, I have to write same block twice...

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.

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.


回答1:


Ok. I've found the answer by trying and looking to refdocs.

get '(:folder/):file', requirements: {  folder: /.*/, file: /.*/ } do

This works as expected.




回答2:


Example:

desc 'Create transaction'
params do
  requires :id, type: String
  requires :from_, type: String
end
post ['/:id/addresses/:from_/transactions', '/:id/transactions'] do

end

Routes:

/api/v1/wallets/:id/addresses/:from_/transactions  
/api/v1/wallets/:id/transactions


来源:https://stackoverflow.com/questions/47755752/how-to-create-two-routes-in-one-block-in-grape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!