methodoverride.rb 803 B

123456789101112131415161718192021222324252627282930313233
  1. module Rack
  2. class MethodOverride
  3. HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS PATCH)
  4. METHOD_OVERRIDE_PARAM_KEY = "_method".freeze
  5. HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze
  6. def initialize(app)
  7. @app = app
  8. end
  9. def call(env)
  10. if env["REQUEST_METHOD"] == "POST"
  11. method = method_override(env)
  12. if HTTP_METHODS.include?(method)
  13. env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"]
  14. env["REQUEST_METHOD"] = method
  15. end
  16. end
  17. @app.call(env)
  18. end
  19. def method_override(env)
  20. req = Request.new(env)
  21. method = req.POST[METHOD_OVERRIDE_PARAM_KEY] ||
  22. env[HTTP_METHOD_OVERRIDE_HEADER]
  23. method.to_s.upcase
  24. rescue EOFError
  25. ""
  26. end
  27. end
  28. end