From 4aeda5c9aa6cd0c8bf344584590c04fd5ef78c32 Mon Sep 17 00:00:00 2001 From: Matt Palmer Date: Tue, 31 Mar 2020 11:00:27 +1100 Subject: [PATCH] Allow HeaderHash#fetch to respect case insensitivity It just makes good sense in general, but it specifically makes the proximate fix for #1629 a lot cleaner. --- lib/rack/utils.rb | 8 ++++++++ test/spec_utils.rb | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/lib/rack/utils.rb b/lib/rack/utils.rb index a0d0354c5..34c5c0265 100644 --- a/lib/rack/utils.rb +++ b/lib/rack/utils.rb @@ -474,6 +474,14 @@ def include?(k) alias_method :member?, :include? alias_method :key?, :include? + def fetch(*args) + begin + super(args.first) + rescue KeyError + super(@names[args.first.downcase], *args[1..-1]) + end + end + def merge!(other) other.each { |k, v| self[k] = v } self diff --git a/test/spec_utils.rb b/test/spec_utils.rb index b39f4a00d..4d8fd84b1 100644 --- a/test/spec_utils.rb +++ b/test/spec_utils.rb @@ -639,6 +639,24 @@ def initialize(*) h.wont_include 'ETag' end + it "fetches values via case-insensitive keys" do + h = Rack::Utils::HeaderHash.new("Content-MD5" => "d5ff4e2a0 ...") + v = h.fetch("content-MD5", "nope") + v.must_equal "d5ff4e2a0 ..." + end + + it "fetches values via case-insensitive keys without defaults" do + h = Rack::Utils::HeaderHash.new("Content-MD5" => "d5ff4e2a0 ...") + v = h.fetch("content-MD5") + v.must_equal "d5ff4e2a0 ..." + end + + it "correctly raises an exception on fetch for a non-existent key" do + h = Rack::Utils::HeaderHash.new("Content-MD5" => "d5ff4e2a0 ...") + + -> { h.fetch("Set-Cookie") }.must_raise(KeyError) + end + it "create deep HeaderHash copy on dup" do h1 = Rack::Utils::HeaderHash.new("Content-MD5" => "d5ff4e2a0 ...") h2 = h1.dup