Class: HTTP::Headers

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/http/headers.rb,
lib/http/headers/known.rb,
lib/http/headers/normalizer.rb

Overview

HTTP Headers container.

Defined Under Namespace

Classes: Normalizer

Constant Summary collapse

ACCEPT =

Content-Types that are acceptable for the response.

"Accept"
ACCEPT_ENCODING =

Content-codings that are acceptable in the response.

"Accept-Encoding"
AGE =

The age the object has been in a proxy cache in seconds.

"Age"
AUTHORIZATION =

Authentication credentials for HTTP authentication.

"Authorization"
CACHE_CONTROL =

Used to specify directives that must be obeyed by all caching mechanisms along the request-response chain.

"Cache-Control"
"Cookie"
CONNECTION =

Control options for the current connection and list of hop-by-hop request fields.

"Connection"
CONTENT_LENGTH =

The length of the request body in octets (8-bit bytes).

"Content-Length"
CONTENT_TYPE =

The MIME type of the body of the request (used with POST and PUT requests).

"Content-Type"
DATE =

The date and time that the message was sent (in “HTTP-date” format as defined by RFC 7231 Date/Time Formats).

"Date"
ETAG =

An identifier for a specific version of a resource, often a message digest.

"ETag"
EXPIRES =

Gives the date/time after which the response is considered stale (in “HTTP-date” format as defined by RFC 7231).

"Expires"
HOST =

The domain name of the server (for virtual hosting), and the TCP port number on which the server is listening. The port number may be omitted if the port is the standard port for the service requested.

"Host"
IF_MODIFIED_SINCE =

Allows a 304 Not Modified to be returned if content is unchanged.

"If-Modified-Since"
IF_NONE_MATCH =

Allows a 304 Not Modified to be returned if content is unchanged.

"If-None-Match"
LAST_MODIFIED =

The last modified date for the requested object (in “HTTP-date” format as defined by RFC 7231).

"Last-Modified"
LOCATION =

Used in redirection, or when a new resource has been created.

"Location"
PROXY_AUTHORIZATION =

Authorization credentials for connecting to a proxy.

"Proxy-Authorization"
"Set-Cookie"
TRANSFER_ENCODING =

The form of encoding used to safely transfer the entity to the user. Currently defined methods are: chunked, compress, deflate, gzip, identity.

"Transfer-Encoding"
CHUNKED =

Chunked transfer coding value for Transfer-Encoding

"chunked"
CONTENT_ENCODING =

Indicates what additional content codings have been applied to the entity-body.

"Content-Encoding"
USER_AGENT =

The user agent string of the user agent.

"User-Agent"
VARY =

Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server.

"Vary"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHeaders

Creates a new empty headers container

Examples:

headers = HTTP::Headers.new


66
67
68
69
70
71
72
# File 'lib/http/headers.rb', line 66

def initialize
  # The @pile stores each header value using a three element array:
  #  0 - the normalized header key, used for lookup
  #  1 - the header key as it will be sent with a request
  #  2 - the value
  @pile = []
end

Class Method Details

.coerce(object) ⇒ Headers Also known as: []

Coerces given object into Headers

Examples:

headers = HTTP::Headers.coerce("Content-Type" => "text/plain")

Parameters:

Returns:

Raises:

  • (Error)

    if object can’t be coerced



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/http/headers.rb', line 25

def coerce(object)
  object = if    object.respond_to?(:to_hash) then object.to_hash
           elsif object.respond_to?(:to_h)    then object.to_h
           elsif object.respond_to?(:to_a)    then object.to_a
           else raise Error, "Can't coerce #{object.inspect} to Headers"
           end

  headers = new
  object.each { |k, v| headers.add k, v }
  headers
end

.normalizerHeaders::Normalizer

Returns the shared normalizer instance

Examples:

HTTP::Headers.normalizer

Returns:



54
55
56
# File 'lib/http/headers.rb', line 54

def normalizer
  @normalizer ||= Normalizer.new #: Headers::Normalizer
end

Instance Method Details

#==(other) ⇒ Boolean

Compares headers to another Headers or Array of pairs

Examples:

headers == other_headers

Returns:

  • (Boolean)


234
235
236
237
238
# File 'lib/http/headers.rb', line 234

def ==(other)
  return false unless other.respond_to? :to_a

  to_a.eql?(other.to_a)
end

#[](name) ⇒ nil, ...

Smart version of #get

Examples:

headers["Content-Type"]

Returns:

  • (nil)

    if header was not set

  • (String)

    if header has exactly one value

  • (Array<String>)

    if header has more than one value



158
159
160
161
162
163
164
165
# File 'lib/http/headers.rb', line 158

def [](name)
  values = get(name)
  return if values.empty?

  return values unless values.one?

  values.join
end

#add(name, value) ⇒ void

This method returns an undefined value.

Appends header value(s) to the given name

Examples:

headers.add("Accept", "text/html")

Parameters:

  • name (String, Symbol)

    header name. When specified as a string, the name is sent as-is. When specified as a symbol, the name is converted to a string of capitalized words separated by a dash. Word boundaries are determined by an underscore (_) or a dash (-). Ex: :content_type is sent as ‘“Content-Type”`, and `“auth_key”` (string) is sent as `“auth_key”`.

  • value (Array<#to_s>, #to_s)

    header value(s) to be appended



124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/http/headers.rb', line 124

def add(name, value)
  lookup_name = normalize_header(name)
  wire_name = wire_name_for(name, lookup_name)

  Array(value).each do |v|
    @pile << [
      lookup_name,
      wire_name,
      validate_value(v)
    ]
  end
end

#deconstruct_keys(keys) ⇒ Hash{Symbol => Object}

Pattern matching interface

Examples:

headers.deconstruct_keys(%i[content_type])

Parameters:

  • keys (Array<Symbol>, nil)

    keys to extract, or nil for all

Returns:

  • (Hash{Symbol => Object})


202
203
204
205
# File 'lib/http/headers.rb', line 202

def deconstruct_keys(keys)
  hash = @pile.map { |_, k, _| k }.to_h { |k| [k.tr("A-Z-", "a-z_").to_sym, self[k]] }
  keys ? hash.slice(*keys) : hash
end

#delete(name) ⇒ void

This method returns an undefined value.

Removes header with the given name

Examples:

headers.delete("Content-Type")

Parameters:

  • name (#to_s)

    header name



105
106
107
108
# File 'lib/http/headers.rb', line 105

def delete(name)
  name = normalize_header name
  @pile.delete_if { |k, _| k.eql?(name) }
end

#eachEnumerator, Headers

Calls the given block once for each key/value pair

Examples:

headers.each { |name, value| puts "#{name}: #{value}" }

Returns:

  • (Enumerator)

    if no block given

  • (Headers)

    self-reference



248
249
250
251
252
253
# File 'lib/http/headers.rb', line 248

def each
  return to_enum unless block_given?

  @pile.each { |item| yield(item.drop(1)) }
  self
end

#empty?Boolean

Returns true if self has no key/value pairs

Examples:

headers.empty?

Returns:

  • (Boolean)


263
# File 'lib/http/headers.rb', line 263

def_delegator :@pile, :empty?

#get(name) ⇒ Array<String>

Returns list of header values if any

Examples:

headers.get("Content-Type")

Returns:

  • (Array<String>)


144
145
146
147
# File 'lib/http/headers.rb', line 144

def get(name)
  name = normalize_header name
  @pile.filter_map { |k, _, v| v if k.eql?(name) }
end

#hashFixnum

Computes a hash-code for this headers container

Examples:

headers.hash

Returns:

  • (Fixnum)

See Also:



274
# File 'lib/http/headers.rb', line 274

def_delegator :@pile, :hash

#include?(name) ⇒ Boolean

Tells whether header with given name is set

Examples:

headers.include?("Content-Type")

Returns:

  • (Boolean)


174
175
176
177
# File 'lib/http/headers.rb', line 174

def include?(name)
  name = normalize_header name
  @pile.any? { |k, _| k.eql?(name) }
end

#initialize_copy(_orig) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Properly clones internal key/value storage



280
281
282
# File 'lib/http/headers.rb', line 280

def initialize_copy(_orig)
  @pile = @pile.map(&:dup)
end

#inspectString

Returns human-readable representation of self instance

Examples:

headers.inspect

Returns:

  • (String)


214
# File 'lib/http/headers.rb', line 214

def inspect = "#<#{self.class}>"

#keysArray<String>

Returns list of header names

Examples:

headers.keys

Returns:

  • (Array<String>)


223
224
225
# File 'lib/http/headers.rb', line 223

def keys
  @pile.map { |_, k, _| k }.uniq
end

#merge(other) ⇒ Headers

Returns new instance with other headers merged in

Examples:

new_headers = headers.merge("Accept" => "text/html")

Returns:

See Also:



306
307
308
# File 'lib/http/headers.rb', line 306

def merge(other)
  dup.tap { |dupped| dupped.merge! other }
end

#merge!(other) ⇒ void

This method returns an undefined value.

Merges other headers into self

Examples:

headers.merge!("Accept" => "text/html")

See Also:



292
293
294
295
296
# File 'lib/http/headers.rb', line 292

def merge!(other)
  coerced = self.class.coerce(other)
  names = coerced.keys
  names.each { |name| set name, coerced.get(name) }
end

#set(name, value) ⇒ void Also known as: []=

This method returns an undefined value.

Sets header, replacing any existing values

Examples:

headers.set("Content-Type", "text/plain")

Parameters:

  • name (String, Symbol)

    header name. When specified as a string, the name is sent as-is. When specified as a symbol, the name is converted to a string of capitalized words separated by a dash. Word boundaries are determined by an underscore (_) or a dash (-). Ex: :content_type is sent as ‘“Content-Type”`, and `“auth_key”` (string) is sent as `“auth_key”`.

  • value (Array<#to_s>, #to_s)

    header value(s) to be appended



82
83
84
85
# File 'lib/http/headers.rb', line 82

def set(name, value)
  delete(name)
  add(name, value)
end

#to_hHash Also known as: to_hash

Returns Rack-compatible headers Hash

Examples:

headers.to_h

Returns:

  • (Hash)


186
187
188
# File 'lib/http/headers.rb', line 186

def to_h
  keys.to_h { |k| [k, self[k]] }
end