Class: Stripe::StripeResponseHeaders
- Inherits:
-
Object
- Object
- Stripe::StripeResponseHeaders
- Defined in:
- lib/stripe/stripe_response.rb
Overview
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.
Class Method Summary collapse
-
.from_net_http(resp) ⇒ Object
Initializes a Headers object from a Net::HTTP::HTTPResponse object.
Instance Method Summary collapse
- #[](name) ⇒ Object
-
#initialize(hash) ⇒ StripeResponseHeaders
constructor
‘hash` is expected to be a hash mapping header names to arrays of header values.
Constructor Details
#initialize(hash) ⇒ StripeResponseHeaders
‘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.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# 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 |
Class Method Details
.from_net_http(resp) ⇒ Object
Initializes a Headers object from a Net::HTTP::HTTPResponse object.
10 11 12 |
# File 'lib/stripe/stripe_response.rb', line 10 def self.from_net_http(resp) new(resp.to_hash) end |
Instance Method Details
#[](name) ⇒ Object
42 43 44 45 46 |
# File 'lib/stripe/stripe_response.rb', line 42 def [](name) values = @hash[name.downcase] warn("Duplicate header values for `#{name}`; returning only first") if values && values.count > 1 values ? values.first : nil end |