Dennis
Dennis

Reputation: 1975

How to create two routes in one block in grape?

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.

Upvotes: 1

Views: 400

Answers (2)

artamonovdev
artamonovdev

Reputation: 2380

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

Upvotes: 1

Dennis
Dennis

Reputation: 1975

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

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

This works as expected.

Upvotes: 3

Related Questions