module Metry module Rack class Tracking COOKIE = "_metry" def initialize(app) @app = app end def call(env) request = ::Rack::Request.new(env) env["metry.event"] = event = build_event(request) env["metry.visitor"] = visitor = find_or_create_visitor(request) status, headers, body = @app.call(env) response = ::Rack::Response.new(body, status, headers) save_visitor(response, visitor) unless event.ignore? event.visitor = visitor event.status = status.to_s event.save end response.to_a end def build_event(request) Event.new("event" => "pageview", :path => request.fullpath, :ip => request.ip, :host => request.host, :method => request.request_method, :referrer => request.env["HTTP_REFERER"], :user_agent => request.env["HTTP_USER_AGENT"]) end def find_or_create_visitor(request) visitor = nil if id = request.cookies[COOKIE] begin visitor = Visitor.find(id) rescue MongoMapper::IllegalID, MongoMapper::DocumentNotFound visitor = nil end end (visitor || Visitor.create) end def save_visitor(response, visitor) visitor.save response.set_cookie(COOKIE, :value => visitor.id.to_s, :expires => (Time.now+(60*60*24*365*20)), :path => '/') end end end end