forked from webmachine/webmachine-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheaders.rb
More file actions
87 lines (77 loc) · 2.4 KB
/
headers.rb
File metadata and controls
87 lines (77 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
require 'webmachine/constants'
module Webmachine
# Case-insensitive Hash of Request headers
class Headers < ::Hash
CGI_HTTP_MATCH = /^HTTP_(\w+)$/.freeze
CONTENT_TYPE_LENGTH_MATCH = /^(CONTENT_(?:TYPE|LENGTH))$/.freeze
# Convert CGI-style Hash into Request headers
# @param [Hash] env a hash of CGI-style env/headers
# @return [Webmachine::Headers]
def self.from_cgi(env)
env.each_with_object(new) do |(k, v), h|
if k =~ CGI_HTTP_MATCH || k =~ CONTENT_TYPE_LENGTH_MATCH
h[$1.tr(UNDERSCORE, DASH)] = v
end
end
end
# Creates a new headers object populated with the given objects.
# It supports the same forms as {Hash.[]}.
#
# @overload [](key, value, ...)
# Pairs of keys and values
# @param [Object] key
# @param [Object] value
# @overload [](array)
# Array of key-value pairs
# @param [Array<Object, Object>, ...]
# @overload [](object)
# Object convertible to a hash
# @param [Object]
# @return [Webmachine::Headers]
def self.[](*args)
super(super.map { |k, v| [k.to_s.downcase, v] })
end
# Fetch a header
def [](key)
super(transform_key(key))
end
# Set a header
def []=(key, value)
super(transform_key(key), value)
end
# Returns the value for the given key. If the key can't be found,
# there are several options:
# With no other arguments, it will raise a KeyError error;
# if default is given, then that will be returned;
# if the optional code block is specified, then that will be run and its
# result returned.
#
# @overload fetch(key)
# A key
# @param [Object] key
# @overload fetch(key, default)
# A key and a default value
# @param [Object] key
# @param [Object] default
# @overload fetch(key) {|key| block }
# A key and a code block
# @param [Object]
# @yield [key] Passes the key to the block
# @return [Object] the value for the key or the default
def fetch(*args, &block)
super(transform_key(args.shift), *args, &block)
end
# Delete a header
def delete(key)
super(transform_key(key))
end
# Select matching headers
def grep(pattern)
self.class[select { |k, _| pattern === k }]
end
private
def transform_key(key)
key.to_s.downcase
end
end # class Headers
end # module Webmachine