rubysinatrapadrino

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.


Solution

  • 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?