Class: Faraday::Utils::Headers

Inherits:
Hash
  • Object
show all
Defined in:
lib/faraday/utils.rb

Overview

Adapted from Rack::Utils::HeaderHash

Constant Summary collapse

KeyMap =

symbol -> string mapper + cache

Hash.new do |map, key|
  map[key] = if key.respond_to?(:to_str) then key
  else
    key.to_s.split('_').            # :user_agent => %w(user agent)
      each { |w| w.capitalize! }.   # => %w(User Agent)
      join('-')                     # => "User-Agent"
  end
end

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Headers

Returns a new instance of Headers.



9
10
11
12
13
# File 'lib/faraday/utils.rb', line 9

def initialize(hash={})
  super()
  @names = {}
  self.update hash
end

Instance Method Details

#[](k) ⇒ Object



32
33
34
35
# File 'lib/faraday/utils.rb', line 32

def [](k)
  k = KeyMap[k]
  super(k) || super(@names[k.downcase])
end

#[]=(k, v) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/faraday/utils.rb', line 37

def []=(k, v)
  k = KeyMap[k]
  k = (@names[k.downcase] ||= k)
  # join multiple values with a comma
  v = v.to_ary.join(', ') if v.respond_to? :to_ary
  super k, v
end

#delete(k) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/faraday/utils.rb', line 45

def delete(k)
  k = KeyMap[k]
  if k = @names[k.downcase]
    @names.delete k.downcase
    super k
  end
end

#include?(k) ⇒ Boolean Also known as: has_key?, member?, key?

Returns:

  • (Boolean)


53
54
55
# File 'lib/faraday/utils.rb', line 53

def include?(k)
  @names.include? k.downcase
end

#initialize_copy(other) ⇒ Object

on dup/clone, we need to duplicate @names hash



16
17
18
19
# File 'lib/faraday/utils.rb', line 16

def initialize_copy(other)
  super
  @names = other.names.dup
end

#merge(other) ⇒ Object



67
68
69
70
# File 'lib/faraday/utils.rb', line 67

def merge(other)
  hash = dup
  hash.merge! other
end

#merge!(other) ⇒ Object Also known as: update



61
62
63
64
# File 'lib/faraday/utils.rb', line 61

def merge!(other)
  other.each { |k, v| self[k] = v }
  self
end

#parse(header_string) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/faraday/utils.rb', line 81

def parse(header_string)
  return unless header_string && !header_string.empty?
  header_string.split(/\r\n/).
    tap  { |a| a.shift if a.first.index('HTTP/') == 0 }. # drop the HTTP status line
    map  { |h| h.split(/:\s+/, 2) }.reject { |p| p[0].nil? }. # split key and value, ignore blank lines
    each { |key, value|
      # join multiple values with a comma
      if self[key] then self[key] << ', ' << value
      else self[key] = value
      end
    }
end

#replace(other) ⇒ Object



72
73
74
75
76
77
# File 'lib/faraday/utils.rb', line 72

def replace(other)
  clear
  @names.clear
  self.update other
  self
end

#to_hashObject



79
# File 'lib/faraday/utils.rb', line 79

def to_hash() ::Hash.new.update(self) end