Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Created March 1, 2016 13:08
Show Gist options
  • Select an option

  • Save tobiashm/73e6286a59a8750be5e3 to your computer and use it in GitHub Desktop.

Select an option

Save tobiashm/73e6286a59a8750be5e3 to your computer and use it in GitHub Desktop.
Simple HTTP OPTIONS response middleware for Rails
module Rack
class OptionsResponse
def initialize(app)
@app = app
end
def call(env)
request = Rack::Request.new(env)
if request.options?
generate_response(request)
else
@app.call(env)
end
end
def generate_response(request)
recognizable_methods = %w(GET PUT POST PATCH DELETE)
allowed_methods = recognizable_methods.select do |method|
begin
Rails.application.routes.recognize_path(request.path, method: method)
rescue ActionController::RoutingError
false
end
end
return [404, {}, []] if allowed_methods.empty?
[204, { "Allow" => %w(HEAD).concat(allowed_methods).join(",") }, []]
end
end
end
Rails.configuration.middleware.use Rack::OptionsResponse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment