Class: HTTY::Headers

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

Overview

Represents the Headers of a Request or a Response. Headers preserve the insertion order and are case insensitive. A custom Hash is used because Hash did not have this behavior in Ruby v1.8.7 and earlier.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Headers

Returns a new instance of Headers.



10
11
12
13
14
15
16
17
# File 'lib/htty/headers.rb', line 10

def initialize(hash={})
  @inner_hash = {}
  @inner_keys = {}
  @ordered_keys = []
  hash.each_pair do |key, value|
    self[key] = value
  end
end

Class Method Details

.basic_authentication_for(username, password = nil) ⇒ Object



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

def self.basic_authentication_for(username, password = nil)
  ['Authorization',
   'Basic ' + Base64.encode64(
     URI.unescape([username, password].compact.join(':'))
    ).chomp
  ]
end

.credentials_from(basic_authentication) ⇒ Object



73
74
75
76
77
78
79
# File 'lib/htty/headers.rb', line 73

def self.credentials_from(basic_authentication)
  if match = /^Basic (.+)$/.match(basic_authentication)
    credentials = Base64.decode64(match[1]).split(':')
    return yield(*credentials) if block_given?
    return credentials
  end
end

Instance Method Details

#==(other_hash) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/htty/headers.rb', line 30

def ==(other_hash)
  if other_hash.kind_of?(self.class)
    return (other_hash.instance_variable_get('@inner_hash') == @inner_hash) &&
           (other_hash.instance_variable_get('@inner_keys') == @inner_keys)
  end
  if other_hash.kind_of?(@inner_hash.class)
    return other_hash.keys.all? do |k|
      other_hash[k] == @inner_hash[k]
    end
  end
  false
end

#[](key) ⇒ Object



19
20
21
# File 'lib/htty/headers.rb', line 19

def [](key)
  @inner_hash[key.downcase]
end

#[]=(key, value) ⇒ Object



23
24
25
26
27
28
# File 'lib/htty/headers.rb', line 23

def []=(key, value)
  @ordered_keys << key.downcase unless @inner_hash.key?(key.downcase)
  @inner_keys[key.downcase] = key
  @inner_hash[key.downcase] = value
  self
end

#clearObject



43
44
45
46
47
# File 'lib/htty/headers.rb', line 43

def clear
  @inner_hash.clear
  @inner_keys.clear
  @ordered_keys.clear
end

#delete(key) ⇒ Object



49
50
51
52
53
# File 'lib/htty/headers.rb', line 49

def delete(key)
  @ordered_keys.delete(key.downcase) if @inner_hash.key?(key.downcase)
  @inner_keys.delete(key.downcase)
  @inner_hash.delete(key.downcase)
end

#empty?Boolean

Returns:

  • (Boolean)


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

def empty?
  @inner_hash.empty?
end

#to_aObject



59
60
61
62
63
# File 'lib/htty/headers.rb', line 59

def to_a
  @ordered_keys.inject([]) do |result, normalized_key|
    result + [[@inner_keys[normalized_key], @inner_hash[normalized_key]]]
  end
end