Better way to defer visit tracking

Andrew Kane committed Jun 17, 2014
commit 570287a6500f98c150d85a6d02eb1ba8954695ff
Showing 4 changed files with 17 additions and 10 deletions
README.md +3 -3
@@ @@ -307,10 +307,10 @@ The visitor and visit id are generated on the server, but the `track_visit` meth
This prevents users with cookies disabled from creating multiple visits and ensures visits are not created for API endpoints.
- Add a before filter to change this:
+ Change this with:
- ```
- before_filter :track_ahoy_visit
+ ```ruby
+ Ahoy.track_visits_on_server = true
```
If you add this to your `ApplicationController`, be sure to exclude API endpoints with:
ahoy.rb b/lib/ahoy.rb +3 -0
@@ @@ -37,6 +37,9 @@ module Ahoy
mattr_accessor :cookie_domain
+ mattr_accessor :track_visits_on_server
+ self.track_visits_on_server = false
+
mattr_accessor :quiet
self.quiet = true
ahoy/controller.rb b/lib/ahoy/controller.rb +2 -1
@@ @@ -7,6 +7,7 @@ module Ahoy
base.helper_method :current_visit
base.helper_method :ahoy
base.before_filter :set_ahoy_cookies
+ base.before_filter :track_ahoy_visit
base.before_filter do
RequestStore.store[:ahoy] ||= ahoy
end
@@ @@ -26,7 +27,7 @@ module Ahoy
end
def track_ahoy_visit
- ahoy.track_visit
+ ahoy.track_visit(defer: !Ahoy.track_visits_on_server)
end
end
ahoy/tracker.rb b/lib/ahoy/tracker.rb +9 -6
@@ @@ -24,11 +24,15 @@ module Ahoy
def track_visit(options = {})
unless exclude? or existing_visit_id
- options = options.dup
+ if options[:defer]
+ set_cookie("ahoy_track", true)
+ else
+ options = options.dup
- options[:started_at] ||= Time.zone.now
+ options[:started_at] ||= Time.zone.now
- @store.track_visit(options)
+ @store.track_visit(options)
+ end
end
true
rescue => e
@@ @@ -59,7 +63,6 @@ module Ahoy
def set_visit_cookie
if !existing_visit_id
set_cookie("ahoy_visit", visit_id, Ahoy.visit_duration)
- set_cookie("ahoy_track", true) # TODO do not set for visits tracked on server
end
end
@@ @@ -89,12 +92,12 @@ module Ahoy
protected
- def set_cookie(name, value, duration)
+ def set_cookie(name, value, duration = nil)
cookie = {
value: value,
- expires: duration.from_now,
path: "/"
}
+ cookie[:expires] = duration.from_now if duration
domain = Ahoy.cookie_domain || Ahoy.domain
cookie[:domain] = domain if domain
controller.response.set_cookie(name, cookie)