Sha256: 5541c7a79dc78b70c7f00c99e1ca3c09db6497b12b9985b729c5a2a4ba2a17ba

Contents?: true

Size: 1.28 KB

Versions: 3

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

require 'forwardable'

module Trav3
  # A header builder class for outgoing requests
  class Headers
    extend Forwardable
    # @!macro [attach] def_delegators
    #   @!method each_pair
    #     Forwards to $1.
    #     @see Hash#each_pair
    #   @!method fetch
    #     Forwards to $1.
    #     @see Hash#fetch
    def_delegators :@heads, :each_pair, :fetch

    def initialize(args = {})
      build(args)
    end

    # Add or update the request headers
    #
    # @return [Headers] self
    def build(args = {})
      @heads ||= {}

      args.each do |(key, value)|
        @heads[key] = value
      end

      self
    end

    # Remove key/value from headers via key
    #
    # @param key [Symbol, String] key to look up
    # @return [String, Symbol, nil] returns value if key found, `nil` otherwise.
    def remove(key)
      @heads.delete(key)
    end

    # Add the values of one `Headers` into another
    #
    # @param other [Headers] instance of `Headers`
    # @return [Headers]
    def +(other)
      raise TypeError, "Headers type expected, #{other.class} given" unless other.is_a? Headers

      @heads.merge(other.instance_variable_get(:@heads))

      self
    end

    # @return [Hash] hash of the `Headers`
    def to_h
      @heads
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
trav3-1.0.0 lib/trav3/headers.rb
trav3-0.5.1 lib/trav3/headers.rb
trav3-0.5.0 lib/trav3/headers.rb