Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verb-agnostic matching in Sinatra

Tags:

ruby

sinatra

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?

like image 686
punund Avatar asked Dec 07 '11 11:12

punund


2 Answers

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.

like image 76
Phrogz Avatar answered Nov 11 '22 07:11

Phrogz


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.

like image 31
Mark Reed Avatar answered Nov 11 '22 06:11

Mark Reed