Sha256: 14214fae3e260b4797f3aa0f0dff42bc50a06e2a0d7aa16a52da8c9a3db7f7f5

Contents?: true

Size: 1002 Bytes

Versions: 5

Compression:

Stored size: 1002 Bytes

Contents

module Low
  module Middleware
    # `RequestId` adds a value for env["request_id"]. `RequestLogger`, for one,
    # uses this value to scope the logger it instantiates.
    class RequestId
      @@request_id = 0

      VALID_REQUEST_ID_REGEX = /^[a-zA-Z0-9\s\-_]*$/

      def self.is_valid?(id)
        id =~ VALID_REQUEST_ID_REGEX
      end

      def initialize(app)
        @app = app

        #generate a request ID (not too worried about uniqueness here).
        @current_request_id = (@@request_id += 1)
      end

      def call(env)
        # If there is a request_id parameter,
        req = Rack::Request.new(env)

        # and it's valid, use it;
        if req['request_id'] and RequestId.is_valid?(req['request_id'])
          env['useless.request_id'] = req['request_id']

        # otherwise, use the generated one
        else
          env['useless.request_id'] = @current_request_id.to_s
        end

        # and call the app.
        @app.call(env)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
low-0.0.12 lib/low/middleware/request_id.rb
low-0.0.11 lib/low/middleware/request_id.rb
low-0.0.10 lib/low/middleware/request_id.rb
low-0.0.9 lib/low/middleware/request_id.rb
low-0.0.8 lib/low/middleware/request_id.rb