Skip to content

Instantly share code, notes, and snippets.

@sheldonh
Created November 14, 2019 15:13
Show Gist options
  • Save sheldonh/6baae12e8e1fad110d518719d4ec57e9 to your computer and use it in GitHub Desktop.
Save sheldonh/6baae12e8e1fad110d518719d4ec57e9 to your computer and use it in GitHub Desktop.
Rack::RequestTimer
require "time"
module Rack
class RequestTimer
class Timer
FORMAT = "%0.3fms elapsed since %s" unless defined?(FORMAT)
attr_reader :start_time
def initialize
@start_time = Time.now
end
def elapsed_seconds
Time.now.to_i - @start_time.to_i
end
def elapsed_milliseconds
(Time.now.to_f - @start_time.to_f) * 1000
end
def to_s
format(FORMAT, elapsed_milliseconds, @start_time)
end
end
ENV_VARIABLE = "rack.request_timer" unless defined?(ENV_VARIABLE)
def initialize(app, env_variable: ENV_VARIABLE)
@app = app
@env_variable = env_variable
end
def call(env)
env[@env_variable] = Timer.new
@app.call(env)
end
def self.timer(env)
env[ENV_VARIABLE]
end
def self.elapsed_seconds(env)
env[ENV_VARIABLE].elapsed_seconds if env[ENV_VARIABLE]
end
def self.elapsed_milliseconds(env)
env[ENV_VARIABLE].elapsed_milliseconds if env[ENV_VARIABLE]
end
end
end
app = ->(env) {
sleep(rand)
[200, {"Content-Type" => "text/plain"}, ["OK: response time: #{Rack::RequestTimer::timer(env)}"]]
}
use Rack::RequestTimer
run app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment