/
analytics.rb
79 lines (71 loc) · 2.51 KB
/
analytics.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
require "split/helper"
module Split
module Analytics
def tracking_code(options={})
# needs more options: http://code.google.com/apis/analytics/docs/gaJS/gaJSApi.html
account = options.delete(:account)
tracker_url = options.delete(:tracker_url)
ssl_tracker_url = options.delete(:ssl_tracker_url)
tracker_methods = options.delete(:tracker_methods)
tracker_url = 'http://' + (tracker_url || 'www.google-analytics.com/ga.js')
ssl_tracker_url = 'https://' + (ssl_tracker_url || 'ssl.google-analytics.com/ga.js')
code = <<-EOF
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '#{account}']);
#{insert_tracker_methods(tracker_methods)}
#{custom_variables}
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? '#{ssl_tracker_url}' : '#{tracker_url}');
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
EOF
code = raw(code)if defined?(raw)
code
end
def custom_variables
return nil if session[:split].nil?
arr = []
session[:split].each_with_index do |h,i|
arr << "_gaq.push(['_setCustomVar', #{i+1}, '#{h[0]}', '#{h[1]}', 1]);"
end
arr.reverse[0..4].reverse.join("\n")
end
private
def insert_tracker_methods(tracker_methods)
return nil if tracker_methods.nil?
arr = []
tracker_methods.each do |k,v|
if v.class == String && v.empty?
# No argument tracker method
arr << "_gaq.push(['" + "_" + "#{k}']);"
else
case v
when String
# String argument tracker method
arr << "_gaq.push(['" + "_" + "#{k}', '#{v}']);"
when TrueClass
# Boolean argument tracker method
arr << "_gaq.push(['" + "_" + "#{k}', #{v}]);"
when FalseClass
# Boolean argument tracker method
arr << "_gaq.push(['" + "_" + "#{k}', #{v}]);"
end
end
end
arr.join("\n")
end
end
end
module Split::Helper
include Split::Analytics
end
if defined?(Rails)
class ActionController::Base
ActionController::Base.send :include, Split::Analytics
ActionController::Base.helper Split::Analytics
end
end