-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
method_override.rb
43 lines (35 loc) · 1.01 KB
/
method_override.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
module Rack
class MethodOverride
HTTP_METHODS = %w[GET HEAD PUT POST DELETE OPTIONS PATCH LINK UNLINK]
METHOD_OVERRIDE_PARAM_KEY = "_method".freeze
HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze
ALLOWED_METHODS = %w[POST]
def initialize(app)
@app = app
end
def call(env)
if allowed_methods.include?(env[REQUEST_METHOD])
method = method_override(env)
if HTTP_METHODS.include?(method)
env[RACK_METHODOVERRIDE_ORIGINAL_METHOD] = env[REQUEST_METHOD]
env[REQUEST_METHOD] = method
end
end
@app.call(env)
end
def method_override(env)
req = Request.new(env)
method = method_override_param(req) ||
env[HTTP_METHOD_OVERRIDE_HEADER]
method.to_s.upcase
end
private
def allowed_methods
ALLOWED_METHODS
end
def method_override_param(req)
req.POST[METHOD_OVERRIDE_PARAM_KEY]
rescue Utils::InvalidParameterError, Utils::ParameterTypeError
end
end
end