Skip to content

Instantly share code, notes, and snippets.

@jacaetevha
Created August 26, 2009 16:13
Show Gist options
  • Save jacaetevha/175613 to your computer and use it in GitHub Desktop.
Save jacaetevha/175613 to your computer and use it in GitHub Desktop.
Add support for the HTTP OPTIONS method to a Sinatra application.
# The HTTP OPTIONS method allows for cross-site HTTP requests.
# For more information see https://developer.mozilla.org/en/HTTP_access_control
# and, of course, the HTTP spec (section 9.2) at http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
# In this example, we plan to use it in development mode only
configure :development do
# Open the Sinatra::Base class and add the method. We can't
# use 'options' as the method name because there is already
# an options method on the class.
class << Sinatra::Base
def http_options path, opts={}, &block
route 'OPTIONS', path, opts, &block
end
end
# This line is necessary if you are using Sinatra in the
# classic (DSL) mode.
Sinatra::Delegator.delegate :http_options
# Finally, set up a route that matches any path and answer
# back that we will allow cross-site requests from any host.
# You obviously wouldn't do this in a production application,
# that would be a huge security risk.
http_options /.+/ do
content_type = 'text/plain'
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Credentials'] = 'true'
response['Access-Control-Max-Age'] = (60 * 60 * 24 * 20).to_s # 20 days, in seconds
''
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment