Class: Metry::Rack::Tracking

Inherits:
Object
  • Object
show all
Defined in:
lib/metry/rack/tracking.rb

Constant Summary collapse

"_metry"

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Tracking

Returns a new instance of Tracking.



6
7
8
# File 'lib/metry/rack/tracking.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#build_event(request) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'lib/metry/rack/tracking.rb', line 30

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

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/metry/rack/tracking.rb', line 10

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

#find_or_create_visitor(request) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/metry/rack/tracking.rb', line 40

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

#save_visitor(response, visitor) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/metry/rack/tracking.rb', line 52

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