Class: Apiphobic::Middleware::Converters::RequestMethod

Inherits:
Object
  • Object
show all
Includes:
Apiphobic::Middleware::Configurable
Defined in:
lib/apiphobic/middleware/converters/request_method.rb

Constant Summary collapse

OVERRIDE_KEY =
'_method'

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Apiphobic::Middleware::Configurable

#configuration, included

Constructor Details

#initialize(app) ⇒ RequestMethod

Returns a new instance of RequestMethod.



16
17
18
# File 'lib/apiphobic/middleware/converters/request_method.rb', line 16

def initialize(app)
  @app = app
end

Instance Attribute Details

#requestObject

Returns the value of attribute request.



14
15
16
# File 'lib/apiphobic/middleware/converters/request_method.rb', line 14

def request
  @request
end

Instance Method Details

#call(env) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/apiphobic/middleware/converters/request_method.rb', line 20

def call(env) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
  self.request      = Rack::Request.new(env)
  allowed_overrides = configuration.allowed_method_overrides

  allowed_overrides.each do |path_pattern, method_mappings|
    path_pattern = path_pattern
                     .gsub(':uuid', '[0-9a-f]{8}\\-(?:[0-9a-f]{4}\\-){3}[0-9a-f]{12}')

    next unless env['PATH_INFO']&.match?(Regexp.new("\\A#{path_pattern}\\z"))

    method_mappings.each do |from, to|
      next unless from.include?(env['REQUEST_METHOD'].downcase)
      next unless to.include?(overridden_method.downcase)

      env['rack.methodoverride.original_method'] = env['REQUEST_METHOD']
      env['REQUEST_METHOD']                      = overridden_method.upcase
    end
  end

  @app.call(env)
end