We can write
get '/foo' do ... end
and
post '/foo' do ... end
which is fine. But can I combine multiple HTTP verbs in one route?
This is possible via the multi-route
extension that is part of sinatra-contrib:
require 'sinatra' require "sinatra/multi_route" route :get, :post, '/foo' do # "GET" or "POST" p request.env["REQUEST_METHOD"] end # Or for module-style applications class MyApp < Sinatra::Base register Sinatra::MultiRoute route :get, :post, '/foo' do # ... end end
However, note that you can do this simply yourself without the extension via:
foo = lambda do # Your route here end get '/foo', &foo post '/foo', &foo
Or more elegantly as a meta-method:
def self.get_or_post(url,&block) get(url,&block) post(url,&block) end get_or_post '/foo' do # ... end
You might also be interested in this discussion on the feature.
FWIW, I just do it manually, with no helper methods or extensions:
%i(get post).each do |method| send method, '/foo' do ... end end
Although if you're doing it a lot it of course makes sense to abstract that out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With