From e65fd65b0e249c970c476042b0f7198186c525c1 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 29 Dec 2008 22:31:27 -0600 Subject: [PATCH] Support X-Http-Method-Override header in MethodOverride middleware --- lib/rack/methodoverride.rb | 7 ++++++- test/spec_rack_methodoverride.rb | 13 ++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/rack/methodoverride.rb b/lib/rack/methodoverride.rb index eb2f0a5..36a1d57 100644 --- a/lib/rack/methodoverride.rb +++ b/lib/rack/methodoverride.rb @@ -2,6 +2,9 @@ module Rack class MethodOverride HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS) + METHOD_OVERRIDE_PARAM_KEY = "_method".freeze + HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze + def initialize(app) @app = app end @@ -9,7 +12,9 @@ module Rack def call(env) if env["REQUEST_METHOD"] == "POST" req = Request.new(env) - method = req.POST["_method"].to_s.upcase + method = req.POST[METHOD_OVERRIDE_PARAM_KEY] || + env[HTTP_METHOD_OVERRIDE_HEADER] + method = method.to_s.upcase if HTTP_METHODS.include?(method) env["REQUEST_METHOD"] = method end diff --git a/test/spec_rack_methodoverride.rb b/test/spec_rack_methodoverride.rb index ac0633e..ad7ab4e 100644 --- a/test/spec_rack_methodoverride.rb +++ b/test/spec_rack_methodoverride.rb @@ -13,7 +13,7 @@ context "Rack::MethodOverride" do req.env["REQUEST_METHOD"].should.equal "GET" end - specify "should modify REQUEST_METHOD for POST requests" do + specify "_method parameter should modify REQUEST_METHOD for POST requests" do env = Rack::MockRequest.env_for("/", :method => "POST", :input => "_method=put") app = Rack::MethodOverride.new(lambda { |env| Rack::Request.new(env) }) req = app.call(env) @@ -21,6 +21,17 @@ context "Rack::MethodOverride" do req.env["REQUEST_METHOD"].should.equal "PUT" end + specify "X-HTTP-Method-Override header should modify REQUEST_METHOD for POST requests" do + env = Rack::MockRequest.env_for("/", + :method => "POST", + "HTTP_X_HTTP_METHOD_OVERRIDE" => "PUT" + ) + app = Rack::MethodOverride.new(lambda { |env| Rack::Request.new(env) }) + req = app.call(env) + + req.env["REQUEST_METHOD"].should.equal "PUT" + end + specify "should not modify REQUEST_METHOD if the method is unknown" do env = Rack::MockRequest.env_for("/", :method => "POST", :input => "_method=foo") app = Rack::MethodOverride.new(lambda { |env| Rack::Request.new(env) }) -- 1.6.0.4