Sha256: 8fd51f77fd3ea3bbb7e0c1c8d07d94553b7cdc4c0834e93f8e9d2ec40f6f1967

Contents?: true

Size: 1.76 KB

Versions: 15

Compression:

Stored size: 1.76 KB

Contents

class SiteHub
  class HttpHeaders < Hash
    HTTP_PREFIX = /^HTTP_/
    RACK_HTTP_HEADER_ID = /#{HTTP_PREFIX.source}[A-Z_]+$/

    class << self
      def from_rack_env(env)
        new(format_keys(remove_rack_specific_headers(env.dup)))
      end

      private

      def remove_rack_specific_headers(env)
        env.reject do |key, value|
          !Constants::RackHttpHeaderKeys::HTTP_HEADER_FILTER_EXCEPTIONS.include?(key.to_s.upcase) &&
            (!RACK_HTTP_HEADER_ID.match(key) || !value)
        end
      end

      def format_keys(env)
        env.each_with_object({}) do |key_value, hash|
          key, value = *key_value
          hash[header_name(key)] = value
        end
      end

      def header_name(name)
        name.sub(HTTP_PREFIX, EMPTY_STRING).downcase.gsub(UNDERSCORE, HYPHEN)
      end
    end

    include Constants, Constants::HttpHeaderKeys

    EXCLUDED_HEADERS = [CONNECTION_HEADER,
                        KEEP_ALIVE,
                        PROXY_CONNECTION,
                        PROXY_AUTHENTICATE,
                        PROXY_AUTHORIZATION,
                        TE,
                        TRAILERS,
                        TRANSFER_ENCODING,
                        CONTENT_ENCODING,
                        UPGRADE].freeze

    def initialize(env)
      env.each do |key, value|
        self[key.to_s.downcase] = value
      end

      filter_prohibited_headers
    end

    private

    def filter_prohibited_headers
      remove_headers(hop_by_hop_headers.concat(EXCLUDED_HEADERS))
    end

    def hop_by_hop_headers
      field = self[CONNECTION_HEADER] || EMPTY_STRING
      field.split(COMMA).collect(&:downcase)
    end

    def remove_headers(excluded)
      reject! do |key, _value|
        excluded.member?(key)
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
sitehub-0.5.0.alpha12 lib/sitehub/http_headers.rb
sitehub-0.4.10 lib/sitehub/http_headers.rb
sitehub-0.5.0.alpha11 lib/sitehub/http_headers.rb
sitehub-0.5.0.alpha10 lib/sitehub/http_headers.rb
sitehub-0.5.0.alpha8 lib/sitehub/http_headers.rb
sitehub-0.5.0.alpha7 lib/sitehub/http_headers.rb
sitehub-0.5.0.alpha6 lib/sitehub/http_headers.rb
sitehub-0.5.0.alpha5 lib/sitehub/http_headers.rb
sitehub-0.5.0.alpha4 lib/sitehub/http_headers.rb
sitehub-0.5.0.alpha3 lib/sitehub/http_headers.rb
sitehub-0.5.0.alpha2 lib/sitehub/http_headers.rb
sitehub-0.4.9 lib/sitehub/http_headers.rb
sitehub-0.4.8 lib/sitehub/http_headers.rb
sitehub-0.4.7 lib/sitehub/http_headers.rb
sitehub-0.4.6 lib/sitehub/http_headers.rb