Sha256: 437e563b6faebca79375ea0ac0133943e3c16010a933657cc9568099b8e03f67

Contents?: true

Size: 1.33 KB

Versions: 16

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

module Rack
  class MethodOverride
    HTTP_METHODS = %w[GET HEAD PUT POST DELETE OPTIONS PATCH LINK UNLINK]

    METHOD_OVERRIDE_PARAM_KEY = "_method"
    HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE"
    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]
      begin
        method.to_s.upcase
      rescue ArgumentError
        env[RACK_ERRORS].puts "Invalid string for method"
      end
    end

    private

    def allowed_methods
      ALLOWED_METHODS
    end

    def method_override_param(req)
      req.POST[METHOD_OVERRIDE_PARAM_KEY]
    rescue Utils::InvalidParameterError, Utils::ParameterTypeError, QueryParser::ParamsTooDeepError
      req.get_header(RACK_ERRORS).puts "Invalid or incomplete POST params"
    rescue EOFError
      req.get_header(RACK_ERRORS).puts "Bad request content body"
    end
  end
end

Version data entries

16 entries across 16 versions & 4 rubygems

Version Path
rack-2.2.10 lib/rack/method_override.rb
blacklight-spotlight-3.6.0.beta8 vendor/bundle/ruby/3.2.0/gems/rack-2.2.9/lib/rack/method_override.rb
cm-admin-1.5.22 vendor/bundle/ruby/3.3.0/gems/rack-2.2.7/lib/rack/method_override.rb
cm-admin-1.5.21 vendor/bundle/ruby/3.3.0/gems/rack-2.2.7/lib/rack/method_override.rb
cm-admin-1.5.20 vendor/bundle/ruby/3.3.0/gems/rack-2.2.7/lib/rack/method_override.rb
rack-2.2.9 lib/rack/method_override.rb
rack-2.2.8.1 lib/rack/method_override.rb
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rack-2.2.7/lib/rack/method_override.rb
rack-2.2.8 lib/rack/method_override.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rack-2.2.7/lib/rack/method_override.rb
rack-2.2.7 lib/rack/method_override.rb
rack-2.2.6.4 lib/rack/method_override.rb
rack-2.2.6.3 lib/rack/method_override.rb
rack-2.2.6.2 lib/rack/method_override.rb
rack-2.2.6.1 lib/rack/method_override.rb
rack-2.2.6 lib/rack/method_override.rb