Permalink
Browse files

prefer composition over inheritence

  • Loading branch information...
1 parent a3ad0a7 commit 6ea781c9a7913ddf75ecdb26a273e194df95b2dc @tenderlove tenderlove committed Oct 18, 2012
Showing with 31 additions and 11 deletions.
  1. +15 −11 actionpack/lib/action_dispatch/http/headers.rb
  2. +16 −0 actionpack/test/dispatch/header_test.rb
@@ -1,31 +1,35 @@
module ActionDispatch
module Http
- class Headers < ::Hash
+ class Headers
+ include Enumerable
+
@@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
+ @headers = args.first || {}
end
def [](header_name)
- super env_name(header_name)
+ @headers[env_name(header_name)]
end
+ def []=(k,v); @headers[k] = v; end
+ def key?(k); @headers.key? k; end
+ alias :include? :key?
+
def fetch(header_name, default=nil, &block)
- super env_name(header_name), default, &block
+ @headers.fetch env_name(header_name), default, &block
+ end
+
+ def each(&block)
+ @headers.each(&block)
end
private
# Converts a HTTP header name to an environment variable name if it is
# not contained within the headers hash.
def env_name(header_name)
- include?(header_name) ? header_name : @@env_cache[header_name]
+ @headers.include?(header_name) ? header_name : @@env_cache[header_name]
end
end
end
@@ -7,6 +7,22 @@ def setup
)
end
+ def test_each
+ headers = []
+ @headers.each { |pair| headers << pair }
+ assert_equal [["HTTP_CONTENT_TYPE", "text/plain"]], headers
+ end
+
+ def test_setter
+ @headers['foo'] = "bar"
+ assert_equal "bar", @headers['foo']
+ end
+
+ def test_key?
+ assert @headers.key?('HTTP_CONTENT_TYPE')
+ assert @headers.include?('HTTP_CONTENT_TYPE')
+ end
+
test "content type" do
assert_equal "text/plain", @headers["Content-Type"]
assert_equal "text/plain", @headers["content-type"]

0 comments on commit 6ea781c

Please sign in to comment.