Sha256: 2dde9f8aff7d8cbdfdcaa4d05dc36472b1db2efd16cd9a03c3cabadce2e77607

Contents?: true

Size: 1.99 KB

Versions: 9

Compression:

Stored size: 1.99 KB

Contents

begin
  require "rack"
rescue LoadError
end

if defined?(::Rack::Request)
  module Timber
    module Util
      # @private
      class Request < ::Rack::Request
        # We store strings as constants since they are reused on a per request basis.
        # This avoids string allocations.
        HTTP_HEADER_ORIGINAL_DELIMITER = '_'.freeze
        HTTP_HEADER_NEW_DELIMITER = '_'.freeze
        HTTP_PREFIX = 'HTTP_'.freeze

        REMOTE_IP_KEY_NAME = 'action_dispatch.remote_ip'.freeze
        REQUEST_ID_KEY_NAME1 = 'action_dispatch.request_id'.freeze
        REQUEST_ID_KEY_NAME2 = 'X-Request-ID'.freeze
        REQUEST_ID_KEY_NAME3 = 'X-Request-Id'.freeze

        def body_content
          content = body.read
          body.rewind
          content
        end

        # Returns a list of request headers. The rack env contains a lot of data, this function
        # identifies those that were the actual request headers.
        #
        # This was extracted from: https://github.com/ruby-grape/grape/blob/91c6c78ae3d3f3ffabaf57ffc4dc35ab7cfc7b5f/lib/grape/request.rb#L30
        def headers
          @headers ||= begin
            headers = {}

            @env.each_pair do |k, v|
              next unless k.is_a?(String) && k.to_s.start_with?(HTTP_PREFIX)

              k = k[5..-1].
                split(HTTP_HEADER_ORIGINAL_DELIMITER).
                each(&:capitalize!).
                join(HTTP_HEADER_NEW_DELIMITER)

              headers[k] = v
            end

            headers
          end
        end

        def ip
          @ip ||= if @env[REMOTE_IP_KEY_NAME]
            @env[REMOTE_IP_KEY_NAME].to_s || super
          else
            super
          end
        end

        def referer
          # Rails 3.X returns "/" for some reason
          @referer ||= super == "/" ? nil : super
        end

        def request_id
          @request_id ||= @env[REQUEST_ID_KEY_NAME1] ||
            @env[REQUEST_ID_KEY_NAME2] ||
            @env[REQUEST_ID_KEY_NAME3]
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
timber-2.6.2 lib/timber/util/request.rb
timber-2.6.1 lib/timber/util/request.rb
timber-2.6.0 lib/timber/util/request.rb
timber-2.6.0.pre.beta2 lib/timber/util/request.rb
timber-2.6.0.pre.beta1 lib/timber/util/request.rb
timber-2.5.1 lib/timber/util/request.rb
timber-2.5.0 lib/timber/util/request.rb
timber-2.4.0 lib/timber/util/request.rb
timber-2.3.4 lib/timber/util/request.rb