Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Several optional parameters in sinatra route

I need the Sinatra route to behave in the following manner:

GET /list/20/10  # Get 20 items with offset 10
GET /list/20     # Get 20 items with default offset
GET /list        # Get default number of items with default offset

I understand, I might pass the values as query:

GET /list?limit=20&offset=10

but I want to pass them as described above. I am pretty sure there is a way to explain to Sinatra/Padrino what I want to do, but I’m currently totally stuck with. I have tried:

get :list, :map => '/list', :with => [:limit, :offset] {} # 404 on /list
get :list, :map => '/list/*' { puts params[:splat] } # 404 on /list
get :list, :map => '/list/?:limit?/?:offset?' {} # 404 on /list
get :list, :map => '/list' { redirect url_for(:list, …) } # 302, not convenient for consumers

How am I supposed to notice Sinatra that the parameter might be optional?

Accidentally,

get %r{/list(/[^/]+)*} do
  # parse params[:captures]
end

works, but that looks silly.

like image 202
Aleksei Matiushkin Avatar asked Feb 18 '14 07:02

Aleksei Matiushkin


2 Answers

This minimal example:

#!/usr/bin/env ruby
require 'sinatra'

get '/test/?:p1?/?:p2?' do
  "Hello #{params[:p1]}, #{params[:p2]}"
end

just works for /test, /test/a and /test/a/b. Did I miss something in your question?

like image 148
To마SE Avatar answered Sep 22 '22 04:09

To마SE


Actually the parameters matching in Sinatra is done by Mustermann and according to the documentation you have several matchers available.

In the sinatra you have:

sinatra     /:slug(.:ext)?

So if you want optional parameters you need to wrap them in ()? like the example above, taken from the documentation.

like image 30
Paulo Fidalgo Avatar answered Sep 26 '22 04:09

Paulo Fidalgo