sinatra路线中的几个可选参数

时间:2021-05-28 11:00:00

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

我需要Sinatra路由以下列方式运行:

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:

但是我想按照上面的描述传递它们。我很确定有一种方法可以向Sinatra / Padrino解释我想做什么,但我现在完全陷入困境。我努力了:

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?

我怎么能注意到Sinatra参数可能是可选的?

Accidentally,

偶然,

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

works, but that looks silly.

有效,但看起来很傻。

2 个解决方案

#1


18  

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?

适用于/ test,/ test / a和/ test / a / b。我错过了你的问题吗?

#2


2  

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

实际上,Sinatra中的参数匹配是由Mustermann完成的,根据文档,您可以使用几个匹配器。

In the sinatra you have:

在sinatra你有:

sinatra     /:slug(.:ext)?

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

所以如果你想要可选参数,你需要将它们包装在()中吗?像上面的例子,取自文档。

#1


18  

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?

适用于/ test,/ test / a和/ test / a / b。我错过了你的问题吗?

#2


2  

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

实际上,Sinatra中的参数匹配是由Mustermann完成的,根据文档,您可以使用几个匹配器。

In the sinatra you have:

在sinatra你有:

sinatra     /:slug(.:ext)?

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

所以如果你想要可选参数,你需要将它们包装在()中吗?像上面的例子,取自文档。