Several optional parameters in sinatra route

Aleksei Matiushkin picture Aleksei Matiushkin · Feb 18, 2014 · Viewed 9.2k times · Source

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.

Answer

To마SE picture To마SE · Feb 18, 2014

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?