简体   繁体   中英

Multiple paths to a single route in sinatra

I want to have multiple urls be handled by the same route handler in sinatra:

At the moment I have:

get 'autocomplete' do

But ideally I would like:

get 'autocomplete_contacts', 'autocomplete_users', 'autocomplete_companies' do

I also need a way of getting the contacts/users/companies part out of the path if that is possible?

Can this be done in sinatra?

You can simply do:

['autocomplete_contacts', 'autocomplete_users', 'autocomplete_companies'].each do |path|
    get path do
        # ...
    end
end

and then retrieve the name of the route by doing:

request.path_info.gsub(/^\/autocomplete_/, '')

inside the handler, which will yields either contacts , users or companies .

If you expect to route all the routes that starts with autocomplete_ you can simply use a regex:

get /^autocomplete_([a-zA-Z])/ do
    # ...
end

and retrieve the name of the route by inspecting params[:captures] .

你可以使用正则表达式:

get %r{(autocomplete_contacts|autocomplete_users|autocomplete_companies)$} do

Use Sinatra MultiRoute Gem - it is what you need! http://www.sinatrarb.com/contrib/multi_route.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM