Skip to content

Instantly share code, notes, and snippets.

@greut
Created October 12, 2009 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greut/208469 to your computer and use it in GitHub Desktop.
Save greut/208469 to your computer and use it in GitHub Desktop.
class LiveStats
def initialize(app, cache, options={})
@app = app
@cache = cache
@period = options[:period] || 3600
@precision = options[:precision] || 10
end
def inc(key, value=1, timeout=nil)
if @cache.incr(key, value).nil?
@cache.add(key, value, timeout || @period)
end
end
def call(env)
env["rack.livestats.track"] = true
now = Time::now
response = @app.call(env)
if env["rack.livestats.track"]
ts = ((Time::now - now) * 1000).to_i # in ms
key = Time::now.to_i / @precision
# time spent
inc("t"+key.to_s, ts)
# visits
inc("v"+key.to_s)
end
response
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment