Created
March 1, 2016 13:08
-
-
Save tobiashm/73e6286a59a8750be5e3 to your computer and use it in GitHub Desktop.
Simple HTTP OPTIONS response middleware for Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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