12

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.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160

2 Answers2

23

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?

To마SE
  • 573
  • 8
  • 19
  • Ooups… Now it works for me like a charm. Looks like the error was induced. Thanks anyway. – Aleksei Matiushkin Feb 18 '14 at 14:06
  • So you need two ? to surround each optional named parameter? – Jwan622 Jan 04 '15 at 03:04
  • Yes, the documentation is very scarce with regards to optional parameters but that's how they are defined. Using a question mark was maybe an awkward decision as it can lead to confusion with the one used for the query string. – To마SE Jan 07 '15 at 03:17
  • 6
    Optional parameters don't need two question marks. A question mark shows that the preceding character or parameter is optional. In this case it shows that the slash is optional, and that the parameter is optional. – Jrgns Jun 11 '15 at 05:24
  • @Jrgns you are absolutely right, the documentation could really do with an explanation of what is the exact effect of the question mark, I'll submit a bug report later on – To마SE Jun 23 '15 at 11:26
4

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.

Paulo Fidalgo
  • 21,709
  • 7
  • 99
  • 115