Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow multiple trackers #52

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ config.middleware.use Rack::GoogleAnalytics, :tracker => 'UA-xxxxxx-x'

### Options

* `:tracker` - sets the Google Analytics tracker
* `:trackers` - array of arrays to set multiple trackers. Takes the form `[['name1', 'tracker1'], ['name2', 'tracker2'], ...]`. Note that `name1` in this example will be ignored because the first tracker is the default. All additional trackers must be named. See https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#multipletrackers for details.
* `:anonymize_ip` - sets the tracker to remove the last octet from all IP addresses, see https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApi_gat?hl=de#_gat._anonymizeIp for details.
* `:domain` - sets the domain name for the GATC cookies. Defaults to `auto`.
* `:site_speed_sample_rate` - Defines a new sample set size for Site Speed data collection, see https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration?hl=de#_gat.GA_Tracker_._setSiteSpeedSampleRate
Expand Down
12 changes: 9 additions & 3 deletions lib/rack/google-analytics.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,14 @@ def _call(env)
env["rack.session"][EVENT_TRACKING_KEY] = env[EVENT_TRACKING_KEY]
end

@options[:tracker] = expand_tracker(env, @options[:tracker])
@tracker = expand_tracker(env, @options[:tracker])
@trackers = expand_trackers(env, @options[:trackers])

@body.each { |fragment| response.write inject(fragment) }
@body.close if @body.respond_to?(:close)

@tracker = nil
@trackers = nil
response.finish
end

Expand All @@ -46,16 +49,19 @@ def _call(env)
def html?; @headers['Content-Type'] =~ /html/; end

def inject(response)
@tracker_options = { cookieDomain: @options[:domain] }.select{|k,v| v }.to_json
@tracker_options = { cookieDomain: @options[:domain] }.select{|k,v| v }
@template ||= ::ERB.new ::File.read ::File.expand_path("../templates/async.erb",__FILE__)

response.gsub(%r{</head>}, @template.result(binding) + "</head>")
end

def expand_tracker(env, tracker)
tracker.respond_to?(:call) ? tracker.call(env) : tracker
end

def expand_trackers(env, trackers)
trackers.respond_to?(:call) ? trackers.call(env) : trackers
end

end

end
24 changes: 20 additions & 4 deletions lib/rack/templates/async.erb
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
<script type="text/javascript">

<% if @options[:tracker] %>
<% if @tracker || @trackers %>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', '<%= @options[:tracker] %>', <%= @tracker_options %>);
<% if @tracker %>
ga('create', '<%= @tracker %>', <%= @tracker_options.to_json %>);
<% else %>
<% @trackers.each_with_index do |pair, i| %>
<% name, tracker = pair %>
ga('create', '<%= tracker %>', <%= (i > 0 ? @tracker_options.merge(:name => name) : @tracker_options).to_json %>);
<% end %>
<% end %>

<% if @options[:enhanced_link_attribution] %>
ga('require', 'linkid', 'linkid.js');
Expand Down Expand Up @@ -40,8 +47,17 @@
ga('require', 'ecommerce', 'ecommerce.js');
<% end %>

<% if @options[:tracker] %>
ga('send', 'pageview');
<% if @tracker %>
ga('send', 'pageview');
<% elsif @trackers %>
<% @trackers.each_with_index do |pair, i| %>
<% name, tracker = pair %>
<% if i == 0 %>
ga('send', 'pageview');
<% else %>
ga('<%= name %>.send', 'pageview');
<% end %>
<% end %>
<% end %>

</script>
36 changes: 36 additions & 0 deletions test/test_rack-google-analytics.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@ class TestRackGoogleAnalytics < Test::Unit::TestCase
get '/'
assert_match %r{ga\('create', 'foobar', {}\)}, last_response.body
end

# TODO couldn't figure out how to alter the env for the same app
# should 'call tracker lambdas for each request' do
# get '/'
# assert_match %r{ga\('create', 'foobar', {}\)}, last_response.body
# # TODO magically change env['misc'] to "beeblebrax"
# get '/'
# assert_match %r{ga\('create', 'beeblebrax', {}\)}, last_response.body
# end
end

context 'adjusted bounce rate' do
Expand All @@ -99,6 +108,33 @@ class TestRackGoogleAnalytics < Test::Unit::TestCase
end
end

context "with multiple trackers" do
setup { mock_app trackers: [['name1','horchata'], ['name2','slurpee']]}
should "show multiple trackers" do
get "/"
assert_match %r{ga\('create', 'horchata', {}\)}, last_response.body
assert_match %r{ga\('create', 'slurpee', {"name":"name2"}\)}, last_response.body
end
should "should trigger pageview for each tracker" do
get "/"
assert_match %r{ga\('send', 'pageview'\);}, last_response.body
assert_match %r{ga\('name2.send', 'pageview'\);}, last_response.body
end
end

context "with multiple trackers block" do
setup do
mock_app trackers: lambda {|env|
[['name1','horchata'], ['name2','slurpee']]
}
end
should "show multiple trackers" do
get "/"
assert_match %r{ga\('create', 'horchata', {}\)}, last_response.body
assert_match %r{ga\('create', 'slurpee', {"name":"name2"}\)}, last_response.body
end
end

# context "with custom _setSiteSpeedSampleRate" do
# setup { mock_app :async => true, :tracker => 'happy', :site_speed_sample_rate => 5 }
# should "add top_level domain script" do
Expand Down