Sha256: 8c571032f1f4f74f5259d16c5f415d3d9613d0fb838cbcfe74f6aa293058b84a

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

module Browser; module HTTP

# Represents a single HTTP header.
Header = Struct.new(:name, :value)

# Represents HTTP headers.
class Headers
  # Parse HTTP headers from a string.
  #
  # @param string [String] the whole HTTP headers response
  # @return [Headers] the parsed headers
  def self.parse(string)
    self[string.lines.map { |l| l.chomp.split(/\s*:\s*/) }]
  end

  # Create {Headers} from a hash.
  def self.[](hash)
    result = new

    hash.each {|name, value|
      result[name] = value
    }

    result
  end

  include Enumerable

  # Create an empty {Headers}.
  def initialize
    @hash = Hash.new
  end

  # Iterate over the headers.
  #
  # @yield [name, value] the header name and value
  # @return [self]
  def each(&block)
    return enum_for :each unless block

    @hash.each {|_, header|
      block.call [header.name, header.value]
    }

    self
  end

  # Get the value of a header.
  def [](name)
    @hash[name.downcase]
  end

  def []=(name, value)
    header = Header.new(name, value)

    @hash[name.downcase] = header
  end

  # Push a header.
  #
  # @param header [Header] the header to push
  # @return [self]
  def <<(header)
    @hash[header.name.downcase] = header

    self
  end

  alias push <<

  # Merge in place other headers.
  #
  # @param other [Headers, Hash, #each] the headers to merge
  # @return [self]
  def merge!(other)
    other.each {|name, value|
      self[name] = value
    }

    self
  end

  # @!attribute [r] length
  # @return [Integer] the number of headers
  def length
    @hash.length
  end
end

end; end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
opal-browser-0.1.0.beta1 opal/browser/http/headers.rb