Created
December 4, 2012 07:45
-
-
Save cbrumelle/4201606 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Currently in Rails 2 and 3... | |
# https://github.com/rails/rails/blob/3-2-stable/actionpack/lib/action_dispatch/http/headers.rb | |
# | |
# headers = ActionDispatch::Http::Headers.new | |
# headers['HTTP_FOO_BAR'] = 'a1b2c3' | |
# puts headers['foo-bar'] #=> 'a1b2c3' | |
# puts headers.has_key? 'foo-bar' #=> false | |
# puts headers.has_key? 'HTTP_FOO_BAR' #=> true | |
# | |
# I found this pseudo hash syntax, where the array [] lookup returned a value, | |
# but include?, has_key? and friends don't work, confusing, inconsistent and surprising. | |
# | |
# Below is a possible fix. | |
module ActionDispatch | |
module Http | |
class Headers < ::Hash | |
@@env_cache = Hash.new { |h,k| h[k] = "HTTP_#{k.upcase.gsub(/-/, '_')}" } | |
def initialize(*args) | |
if args.size == 1 && args[0].is_a?(Hash) | |
super() | |
update(args[0]) | |
else | |
super | |
end | |
end | |
def [](header_name) | |
super || super(env_name(header_name)) | |
end | |
def key?(header_name) | |
!!self[header_name] | |
end | |
alias_method :include?, :key? | |
alias_method :has_key?, :key? | |
alias_method :member?, :key? | |
private | |
# Converts a HTTP header name to an environment variable name. | |
def env_name(header_name) | |
@@env_cache[header_name] | |
end | |
end | |
end | |
end | |
# ==================== | |
# Testing.... | |
# ==================== | |
headers = ActionDispatch::Http::Headers.new | |
headers['HTTP_FOO_BAR'] = 'ab123cd' | |
puts headers['foo-bar'] #=> 'ab123cd' | |
puts headers['HTTP_FOO_BAR'] #=> 'ab123cd' | |
puts headers.has_key? 'foo-bar' # => true | |
puts headers.has_key? 'HTTP_FOO_BAR' # => true | |
puts headers.key? 'foo-bar' # => true | |
puts headers.key? 'HTTP_FOO_BAR' # => true | |
puts headers.member? 'foo-bar' # => true | |
puts headers.member? 'HTTP_FOO_BAR' # => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment