kangguru / rack-google-analytics

Simple Rack middleware for implementing google analytics tracking in your Ruby-Rack based project. Supports synchronous and asynchronous insertion and configurable load options
MIT License
257 stars 53 forks source link

Add track_pageview option to make it easier to use with Turbolinks #45

Closed remi closed 8 years ago

remi commented 10 years ago

This pull request adds a track_pageview option (which is true by default, to keep existing behavior). When used, it does not output the ga('send', 'pageview') line in the tracker code.

We’re using this to make the middleware play nice with Turbolinks which does not evaluate <script> tags in the <head> when changing pages. This new track_pageview option allows us to have this code in the <head>.

<head>
  …

  <script type="text/javascript">
    (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', 'UA-0000000-01', {});
  </script>
</head>
<body>
  …
</body>

And manually track our pageviews in a <script> element at the end of our <body> (which gets evaluated by Turbolinks when it changes the page content)

<head>
  …
</head>
<body>
  …
  <script>
    if (window.ga) { ga('send', 'pageview'); }
  </script>
</body>

What do you think? It doesn’t do anything if the option is not used :smile:

remi commented 10 years ago

Looks like travis has got problems with the Rubinius build… Tests pass fine on 1.9.3, 2.0.0 and 2.1.0.

kangguru commented 10 years ago

yea. don't care about the rbx failure ;)

is it causing a problem if the ga('send', 'pageview'); is triggered in the head when using Turbolinks?

Wouldn't it be better if the location, where the code is inserted into the page, is configurable? So you can still use the controller actions.

I'm thinking about something like

use Rack::GoogleAnalytics, tracker: 'UA-xxxxxx-x', location: :body # insert event at the right before </body>

But i never got to use Turbolinks, do you think this would work and be usable?

remi commented 8 years ago

I’m going to close this pull request since we’re using rack-tracker now.