Skip to content

Instantly share code, notes, and snippets.

@ChunAllen
Created April 15, 2015 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChunAllen/b6e181c284fb42703ca0 to your computer and use it in GitHub Desktop.
Save ChunAllen/b6e181c284fb42703ca0 to your computer and use it in GitHub Desktop.
Google Analytics for Ruby on Rails
class @GoogleAnalytics
@load: ->
# Load the analytics code
window['GoogleAnalyticsObject'] = 'ga'
window['ga'] = window['ga'] || ->
(window['ga'].q = window['ga'].q || []).push arguments
window['ga'].l = 1 * new Date()
# Add the script
googleScript = document.createElement("script")
googleScript.async = 1
googleScript.src = '//www.google-analytics.com/analytics.js'
firstScript = document.getElementsByTagName("script")[0]
firstScript.parentNode.insertBefore googleScript, firstScript
# Create the analytics
ga 'create', GoogleAnalytics.analyticsId(), 'auto'
# You can enable additional modules like so
# ga 'require', 'displayfeatures'
if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
document.addEventListener "page:change", GoogleAnalytics.trackPageview, true
else
GoogleAnalytics.trackPageview()
@trackPageview: (url) ->
unless GoogleAnalytics.isLocalRequest()
if url
ga 'send', 'pageview', url
else
ga 'send', 'pageview'
@isLocalRequest: ->
document.domain.indexOf('dev') isnt -1
@analyticsId: ->
'[change-this-to-analytics-id]'
GoogleAnalytics.load()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment