Class: WebMock::Util::Headers

Inherits:
Object
  • Object
show all
Defined in:
lib/webmock/util/headers.rb

Constant Summary collapse

STANDARD_HEADER_DELIMITER =
'-'
NONSTANDARD_HEADER_DELIMITER =
'_'
JOIN =
', '

Class Method Summary collapse

Class Method Details

.basic_auth_header(*credentials) ⇒ Object



59
60
61
62
# File 'lib/webmock/util/headers.rb', line 59

def self.basic_auth_header(*credentials)
  strict_base64_encoded = [credentials.join(':')].pack("m0")
  "Basic #{strict_base64_encoded.chomp}"
end

.decode_userinfo_from_header(header) ⇒ Object



55
56
57
# File 'lib/webmock/util/headers.rb', line 55

def self.decode_userinfo_from_header(header)
  header.sub(/^Basic /, "").unpack("m").first
end

.normalize_headers(headers) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/webmock/util/headers.rb', line 13

def self.normalize_headers(headers)
  return nil unless headers

  headers.each_with_object({}) do |(name, value), new_headers|
    new_headers[normalize_name(name)] =
      case value
      when Regexp then value
      when Array then (value.size == 1) ? value.first.to_s : value.map(&:to_s).sort
      else value.to_s
      end
  end
end

.normalize_name(name) ⇒ Object



64
65
66
67
68
69
70
71
# File 'lib/webmock/util/headers.rb', line 64

def self.normalize_name(name)
  name
    .to_s
    .tr(NONSTANDARD_HEADER_DELIMITER, STANDARD_HEADER_DELIMITER)
    .split(STANDARD_HEADER_DELIMITER)
    .map!(&:capitalize)
    .join(STANDARD_HEADER_DELIMITER)
end

.pp_headers_string(headers) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/webmock/util/headers.rb', line 40

def self.pp_headers_string(headers)
  headers = WebMock::Util::Headers.normalize_headers(headers)
  seperator = "\n\t "
  str = "{#{seperator} ".dup
  str << headers.map do |k,v|
    v = case v
      when Regexp then v.inspect
      when Array then "["+v.map{|w| "'#{w.to_s}'"}.join(", ")+"]"
      else "'#{v.to_s}'"
    end
    "'#{k}'=>#{v}"
  end.sort.join(",#{seperator} ")
  str << "\n    }"
end

.sorted_headers_string(headers) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/webmock/util/headers.rb', line 26

def self.sorted_headers_string(headers)
  headers = WebMock::Util::Headers.normalize_headers(headers)
  str = '{'.dup
  str << headers.map do |k,v|
    v = case v
      when Regexp then v.inspect
      when Array then "["+v.map{|w| "'#{w.to_s}'"}.join(", ")+"]"
      else "'#{v.to_s}'"
    end
    "'#{k}'=>#{v}"
  end.sort.join(", ")
  str << '}'
end