Class: HTTP::Headers::Normalizer

Inherits:
Object
  • Object
show all
Defined in:
lib/http/headers/normalizer.rb,
sig/http.rbs

Overview

Normalizes HTTP header names to canonical form

Constant Summary collapse

COMPLIANT_NAME_RE =

Matches valid header field name according to RFC.

/\A[A-Za-z0-9!#$%&'*+\-.^_`|~]+\z/
NAME_PARTS_SEPARATOR_RE =

Pattern matching header name part separators (hyphens and underscores)

Returns:

  • (Regexp)
/[-_]/
CACHE_KEY =

Thread-local cache key for normalized header names

Returns:

  • (Symbol)
:http_headers_normalizer_cache

Instance Method Summary collapse

Instance Method Details

#call(name) ⇒ String

Normalizes a header name to canonical form

Examples:

normalizer.call("content-type")

Parameters:

  • name (String, Symbol)

Returns:

  • (String)


24
25
26
27
28
29
30
# File 'lib/http/headers/normalizer.rb', line 24

def call(name)
  name  = name.to_s
  cache = (Thread.current[CACHE_KEY] ||= {})
  value = (cache[name] ||= normalize_header(name))

  value.dup
end

#normalize_header(name) ⇒ String

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.

Transforms name to canonical HTTP header capitalization

Parameters:

  • name (String)

Returns:

  • (String)

    canonical HTTP header name

Raises:



41
42
43
44
45
46
47
# File 'lib/http/headers/normalizer.rb', line 41

def normalize_header(name)
  normalized = name.split(NAME_PARTS_SEPARATOR_RE).each(&:capitalize!).join("-")

  return normalized if COMPLIANT_NAME_RE.match?(normalized)

  raise HeaderError, "Invalid HTTP header field name: #{name.inspect}"
end