Universal Analytics with Turbolinks and Gon
A quick quick guide to make Universal Analytics play nicely with Turbolinks.
<a href="https://github.com/rails/turbolinks", alt="Turoblinks - Github" rel="nofollow" target="_blank" >Turbolinks can boost your Rails 4 app performance but will cause unexpected behavior if you don't plan ahead. Client-side analytics libraries, like Google Analytics, will not function out of the box with Turbolinks and I will walk-through how to make Universal Analytics play nicely with Turbolinks.
For some quick background, while conducting research, I found a few issues with existing Google Analytics / Turbolinks solutions out there. These included:
settings.ymlfile with other important keys. Loading from a settings file makes it easier to switch out keys, allowing me to test custom events, dimensions and other goodies on a staging server.
- Virtually every solution I found was built on Classic Analytics, which is being depreciated, rather than the newer Universal Analytics.
- None of the configurations I found handled custom events, dimensions, metrics, e-commerce and other important functionality. (Note: this will be covered in a separate post)
This is the most important part of the configuration:
@analyticsId: -> gon.google_analytics_id
This is where the key from our
application_controller.rb and a Gon helper method the application head.
# application_controller.rb before_action :set_gon_google_analytics_id private def set_gon_google_analtyics_id gon.google_analtyics_id = Rails.application.secrets.google_analytics_id end
A future post will walk through setting up events and social tracking with a Turbolinks-compatible setup. For reference, here are some other resources to check out:
- Turbolinks / Google Analytics Compatibility
- Rails Apps - Google Analytics</a?