[](key)
click to toggle source
Returns the header field corresponding to the case-insensitive key. For example, a key of “Content-Type” might return “text/html”
def [](key)
a = @header[key.downcase.to_s] or return nil
a.join(', ')
end
[]=(key, val)
click to toggle source
Sets the header field corresponding to the case-insensitive key.
def []=(key, val)
unless val
@header.delete key.downcase.to_s
return val
end
set_field(key, val)
end
add_field(key, val)
click to toggle source
- Ruby 1.8.3
-
Adds a value to a named header field, instead of replacing its value. Second argument val
must be a String. See also []=
, []
and get_fields
.
request.add_field 'X-My-Header', 'a'
p request['X-My-Header']
p request.get_fields('X-My-Header')
request.add_field 'X-My-Header', 'b'
p request['X-My-Header']
p request.get_fields('X-My-Header')
request.add_field 'X-My-Header', 'c'
p request['X-My-Header']
p request.get_fields('X-My-Header')
def add_field(key, val)
stringified_downcased_key = key.downcase.to_s
if @header.key?(stringified_downcased_key)
append_field_value(@header[stringified_downcased_key], val)
else
set_field(key, val)
end
end
basic_auth(account, password)
click to toggle source
Set the Authorization: header for “Basic” authorization.
def basic_auth(account, password)
@header['authorization'] = [basic_encode(account, password)]
end
canonical_each()
click to toggle source
chunked?()
click to toggle source
Returns “true” if the “transfer-encoding” header is present and set to “chunked”. This is an HTTP/1.1 feature, allowing the content to be sent in “chunks” without at the outset stating the entire content length.
def chunked?
return false unless @header['transfer-encoding']
field = self['Transfer-Encoding']
(/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
end
connection_close?()
click to toggle source
def connection_close?
token = /(?:\A|,)\s*close\s*(?:\z|,)/i
@header['connection']&.grep(token) {return true}
@header['proxy-connection']&.grep(token) {return true}
false
end
connection_keep_alive?()
click to toggle source
def connection_keep_alive?
token = /(?:\A|,)\s*keep-alive\s*(?:\z|,)/i
@header['connection']&.grep(token) {return true}
@header['proxy-connection']&.grep(token) {return true}
false
end
content_length()
click to toggle source
Returns an Integer object which represents the HTTP
Content-Length: header field, or nil
if that field was not provided.
def content_length
return nil unless key?('Content-Length')
len = self['Content-Length'].slice(/\d+/) or
raise Net::HTTPHeaderSyntaxError, 'wrong Content-Length format'
len.to_i
end
content_length=(len)
click to toggle source
def content_length=(len)
unless len
@header.delete 'content-length'
return nil
end
@header['content-length'] = [len.to_i.to_s]
end
content_range()
click to toggle source
Returns a Range object which represents the value of the Content-Range: header field. For a partial entity body, this indicates where this fragment fits inside the full entity body, as range of byte offsets.
def content_range
return nil unless @header['content-range']
m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
raise Net::HTTPHeaderSyntaxError, 'wrong Content-Range format'
m[1].to_i .. m[2].to_i
end
content_type()
click to toggle source
Returns a content type string such as “text/html”. This method returns nil if Content-Type: header field does not exist.
def content_type
return nil unless main_type()
if sub_type()
then "#{main_type()}/#{sub_type()}"
else main_type()
end
end
content_type=(type, params = {})
click to toggle source
delete(key)
click to toggle source
Removes a header field, specified by case-insensitive key.
def delete(key)
@header.delete(key.downcase.to_s)
end
each()
click to toggle source
each_capitalized()
click to toggle source
As for each_header
, except the keys are provided in capitalized form.
Note that header names are capitalized systematically; capitalization may not match that used by the remote HTTP
server in its response.
Returns an enumerator if no block is given.
def each_capitalized
block_given? or return enum_for(__method__) { @header.size }
@header.each do |k,v|
yield capitalize(k), v.join(', ')
end
end
each_capitalized_name()
click to toggle source
Iterates through the header names in the header, passing capitalized header names to the code block.
Note that header names are capitalized systematically; capitalization may not match that used by the remote HTTP
server in its response.
Returns an enumerator if no block is given.
def each_capitalized_name
block_given? or return enum_for(__method__) { @header.size }
@header.each_key do |k|
yield capitalize(k)
end
end
each_key()
click to toggle source
each_name()
click to toggle source
Iterates through the header names in the header, passing each header name to the code block.
Returns an enumerator if no block is given.
def each_name(&block)
block_given? or return enum_for(__method__) { @header.size }
@header.each_key(&block)
end
each_value()
click to toggle source
Iterates through header values, passing each value to the code block.
Returns an enumerator if no block is given.
def each_value
block_given? or return enum_for(__method__) { @header.size }
@header.each_value do |va|
yield va.join(', ')
end
end
fetch(key, *args)
click to toggle source
Returns the header field corresponding to the case-insensitive key. Returns the default value args
, or the result of the block, or raises an IndexError if there's no header field named key
See Hash#fetch
def fetch(key, *args, &block)
a = @header.fetch(key.downcase.to_s, *args, &block)
a.kind_of?(Array) ? a.join(', ') : a
end
get_fields(key)
click to toggle source
- Ruby 1.8.3
-
Returns an array of header field strings corresponding to the case-insensitive key
. This method allows you to get duplicated header fields without any processing. See also []
.
p response.get_fields('Set-Cookie')
#=> ["session=al98axx; expires=Fri, 31-Dec-1999 23:58:23",
"query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"]
p response['Set-Cookie']
#=> "session=al98axx; expires=Fri, 31-Dec-1999 23:58:23, query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"
def get_fields(key)
stringified_downcased_key = key.downcase.to_s
return nil unless @header[stringified_downcased_key]
@header[stringified_downcased_key].dup
end
key?(key)
click to toggle source
true if key
header exists.
def key?(key)
@header.key?(key.downcase.to_s)
end
main_type()
click to toggle source
Returns a content type string such as “text”. This method returns nil if Content-Type: header field does not exist.
def main_type
return nil unless @header['content-type']
self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
end
proxy_basic_auth(account, password)
click to toggle source
Set Proxy-Authorization: header for “Basic” authorization.
def proxy_basic_auth(account, password)
@header['proxy-authorization'] = [basic_encode(account, password)]
end
range()
click to toggle source
Returns an Array of Range objects which represent the Range: HTTP
header field, or nil
if there is no such header.
def range
return nil unless @header['range']
value = self['Range']
unless /\Abytes=((?:,[ \t]*)*(?:\d+-\d*|-\d+)(?:[ \t]*,(?:[ \t]*\d+-\d*|-\d+)?)*)\z/ =~ value
raise Net::HTTPHeaderSyntaxError, "invalid syntax for byte-ranges-specifier: '#{value}'"
end
byte_range_set = $1
result = byte_range_set.split(/,/).map {|spec|
m = /(\d+)?\s*-\s*(\d+)?/i.match(spec) or
raise Net::HTTPHeaderSyntaxError, "invalid byte-range-spec: '#{spec}'"
d1 = m[1].to_i
d2 = m[2].to_i
if m[1] and m[2]
if d1 > d2
raise Net::HTTPHeaderSyntaxError, "last-byte-pos MUST greater than or equal to first-byte-pos but '#{spec}'"
end
d1..d2
elsif m[1]
d1..-1
elsif m[2]
-d2..-1
else
raise Net::HTTPHeaderSyntaxError, 'range is not specified'
end
}
if result.size == 1 && result[0].begin == 0 && result[0].end == -1
raise Net::HTTPHeaderSyntaxError, 'only one suffix-byte-range-spec with zero suffix-length'
end
result
end
range=(r, e = nil)
click to toggle source
range_length()
click to toggle source
The length of the range represented in Content-Range: header.
def range_length
r = content_range() or return nil
r.end - r.begin + 1
end
set_content_type(type, params = {})
click to toggle source
Sets the content type in an HTTP
header. The type
should be a full HTTP
content type, e.g. “text/html”. The params
are an optional Hash of parameters to add after the content type, e.g. {'charset' => 'iso-8859-1'}
def set_content_type(type, params = {})
@header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
end
set_range(r, e = nil)
click to toggle source
Sets the HTTP
Range: header. Accepts either a Range object as a single argument, or a beginning index and a length from that index. Example:
req.range = (0..1023)
req.set_range 0, 1023
def set_range(r, e = nil)
unless r
@header.delete 'range'
return r
end
r = (r...r+e) if e
case r
when Numeric
n = r.to_i
rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
when Range
first = r.first
last = r.end
last -= 1 if r.exclude_end?
if last == -1
rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
else
raise Net::HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
raise Net::HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
raise Net::HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
rangestr = "#{first}-#{last}"
end
else
raise TypeError, 'Range/Integer is required'
end
@header['range'] = ["bytes=#{rangestr}"]
r
end
sub_type()
click to toggle source
Returns a content type string such as “html”. This method returns nil if Content-Type: header field does not exist or sub-type is not given (e.g. “Content-Type: text”).
def sub_type
return nil unless @header['content-type']
_, sub = *self['Content-Type'].split(';').first.to_s.split('/')
return nil unless sub
sub.strip
end
to_hash()
click to toggle source
Returns a Hash consisting of header names and array of values. e.g. {“cache-control” => [“private”],
"content-type" => ["text/html"],
"date" => ["Wed, 22 Jun 2005 22:11:50 GMT"]}
def to_hash
@header.dup
end
type_params()
click to toggle source
Any parameters specified for the content type, returned as a Hash. For example, a header of Content-Type: text/html; charset=EUC-JP would result in type_params
returning {'charset' => 'EUC-JP'}
def type_params
result = {}
list = self['Content-Type'].to_s.split(';')
list.shift
list.each do |param|
k, v = *param.split('=', 2)
result[k.strip] = v.strip
end
result
end