Is there a way to match urls with Sinatra using question mark?

get '/:id?inspect' do
  # ...
end

get '/:id?last' do
  # ...
end

get '/:id' do
  # ...
end

I tried escaping the question mark \?, regex etc, but none of those worked.

I don't want to retrieve the value of inspect or last. I only want to know if they were supplied in the url.

Is that possible?

有帮助吗?

解决方案

You can’t directly do what you want. When describing the route, Sinatra treats ? as defining an optional parameter, and doesn’t provide a way to escape it.

In a url a ? separates the path from the query string, and Sinatra only uses the path when matching routes. The contents of the query string are parsed and available in params, and the raw string is available as request.query_string.

Your url scheme seems rather unusual, but one possibility if you want to avoid checking the query_string in the actual route could be to create a custom condition to apply to the routes, and check in there:

set(:query) { |val| condition { request.query_string == val } }

get '/:id', :query => 'inspect' do
  # ...
end

get '/:id', :query => 'last' do
  # ...
end

get '/:id' do
  # ...
end

其他提示

A standard route is not defined by query parameters and should not be. Why don't you use a if construct on the params in the get /:id route?

I also suggest that when you want to set a query parameter in the request you set it like this: /:id?inspect=true (provide a dummy value)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top