문제

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.

도움이 되었습니까?

해결책

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?

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top