15

Does Sinatra support the OPTIONS HTTP verb? Something like:

options '/' do
  response.headers["Access-Control-Allow-Origin"] = "*"
  response.headers["Access-Control-Allow-Methods"] = "POST"

  halt 200
end
Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232

4 Answers4

30

After a bit of hacking I managed to get it working using:

before do
  if request.request_method == 'OPTIONS'
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "POST"

    halt 200
  end
end

Edit:

After some more looking around on this issue, I realized that a PULL request is up on GitHub for the addition of the OPTIONS verb (https://github.com/sinatra/sinatra/pull/129). I took the solution and hacked it in using the following snippet:

configure do
  class << Sinatra::Base
    def options(path, opts={}, &block)
      route 'OPTIONS', path, opts, &block
    end
  end
  Sinatra::Delegator.delegate :options
end

Now I can simply use:

options '/' do
  ...
end

Edit:

The pull request should be merged. No more need for the hack.

Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
  • 2
    If you are reading this, please check [my answer](http://stackoverflow.com/a/10195704/316700), now Sinatra implements the `options` _method_ out-of-the-box. – fguillen Aug 01 '14 at 08:40
6

Yes, already does it Sinatra Routes documentation

fguillen
  • 36,125
  • 23
  • 149
  • 210
2

No it does not. If you look at the code on GitHub you can see where the HTTP verbs are defined, and options is not one of them.

Jamison Dance
  • 19,896
  • 25
  • 97
  • 99
  • 2
    @KevinSylvestre Given that it appears that the existing route verbs are implemented as class methods on Sinatra::Base (see the link that Jergason gave) you should just be able to define your own: `def Sinatra::Base.options(path,opts={},&bk); route 'OPTIONS', path, opts, &bk end` (untested). – Phrogz Dec 05 '10 at 17:04
  • @Phrogz Thanks! That snippet helped me out in figuring out how to patch it in. See my updated answer. – Kevin Sylvestre Dec 09 '10 at 10:40
0

the answer is, simply, yes! (look under Routes in the read me http://www.sinatrarb.com/intro.html)

carlad
  • 11
  • 3