class Stripe::Headers

Headers provides an access wrapper to an API response's header data. It mainly exists so that we don't need to expose the entire `Net::HTTPResponse` object while still getting some of its benefits like case-insensitive access to header names and flattening of header values.

Public Class Methods

from_net_http(resp) click to toggle source

Initializes a Headers object from a Net::HTTP::HTTPResponse object.

# File lib/stripe/stripe_response.rb, line 10
def self.from_net_http(resp)
  new(resp.to_hash)
end
new(hash) click to toggle source

`hash` is expected to be a hash mapping header names to arrays of header values. This is the default format generated by calling `#to_hash` on a `Net::HTTPResponse` object because headers can be repeated multiple times. Using `#[]` will collapse values down to just the first.

# File lib/stripe/stripe_response.rb, line 19
def initialize(hash)
  if !hash.is_a?(Hash) ||
     !hash.keys.all? { |n| n.is_a?(String) } ||
     !hash.values.all? { |a| a.is_a?(Array) } ||
     !hash.values.all? { |a| a.all? { |v| v.is_a?(String) } }
    raise ArgumentError,
          "expect hash to be a map of string header names to arrays of " \
          "header values"
  end

  @hash = {}

  # This shouldn't be strictly necessary because `Net::HTTPResponse` will
  # produce a hash with all headers downcased, but do it anyway just in
  # case an object of this class was constructed manually.
  #
  # Also has the effect of duplicating the hash, which is desirable for a
  # little extra object safety.
  hash.each do |k, v|
    @hash[k.downcase] = v
  end
end

Public Instance Methods

[](name) click to toggle source
# File lib/stripe/stripe_response.rb, line 42
def [](name)
  values = @hash[name.downcase]
  if values && values.count > 1
    warn("Duplicate header values for `#{name}`; returning only first")
  end
  values ? values.first : nil
end