Tracking made easy: Don’t fool around with adding tracking and analytics partials to your app and concentrate on the things that matter.
Tracking made easy: Don’t fool around with adding tracking and analytics partials to your app and concentrate on the things that matter.
Most of the applications we're working on are using some sort of tracking/analytics service,
Google Analytics comes first but its likely that more are added as the project grows.
Normally you'd go ahead and add some partials to your application that will render out the
needed tracking codes. As time passes by you'll find yourself with lots of tracking
snippets, that will clutter your codebase :) When just looking at Analytics there are
solutions like rack-google-analytics but they just soley tackle the existence of one
service.
We wanted a solution that ties all services together in one place and offers
an easy interface to drop in new services. This is why we created rack-tracker, a
rack middleware that can be hooked up to multiple services and exposing them in a unified
fashion. It comes in two parts, the first one is the actual middleware that you can add
to the middleware stack the second part are the service-handlers that you're going to use
in your application. It's easy to add your own custom handlers,
but to get you started we're shipping support for the services mentioned below
out of the box:
The Do Not Track (DNT) HTTP header is a HTTP header that requests the server to disable its tracking of the individual user. This is an opt-out option supported by most browsers. This option is disabled by default and has to be explicitly enabled to indicate the user's request to opt-out. We believe evey application should respect the user's choice to opt-out and respect this HTTP header.
Since version 2.0.0 rack-tracker respects that request header by default. That means NO tracker is injected IF the DNT header is set to "1".
This option can be overwriten using the DO_NOT_RESPECT_DNT_HEADER => true option which must be set on any handler that should ignore the DNT header. (but please think twice before doing that)
use Rack::Tracker do
# this tracker will be injected EVEN IF the DNT header is set to 1
handler :maybe_a_friendly_tracker, { tracker: 'U-XXXXX-Y', DO_NOT_RESPECT_DNT_HEADER: true }
# this tracker will NOT be injected if the DNT header is set to 1
handler :google_analytics, { tracker: 'U-XXXXX-Y' }
endFurther reading on the DNT header:
Add this line to your application's Gemfile:
gem 'rack-tracker'And then execute:
$ bundleOr install it yourself as:
$ gem install rack-trackerAdd it to your middleware stack
config.middleware.use(Rack::Tracker) do
handler :google_analytics, { tracker: 'U-XXXXX-Y' }
endThis will add Google Analytics as a tracking handler.
You can even use Rack::Tracker with Sinatra or respectively with every Rack application
Just insert the Tracker in your Rack stack:
web = Rack::Builder.new do
use Rack::Tracker do
handler :google_analytics, { tracker: 'U-XXXXX-Y' }
end
run Sinatra::Web
end
run webAlthough you cannot use the Rails controller extensions for obvious reasons, its easy to inject arbitrary events into the request environment.
request.env['tracker'] = {
'google_analytics' => [
{ 'class_name' => 'Send', 'category' => 'Users', 'action' => 'Login', 'label' => 'Standard' }
]
}:anonymize_ip - sets the tracker to remove the last octet from all IP addresses, see https://developers.google.com/analytics/devguides/collection/gtagjs/ip-anonymization for details.:cookie_domain - sets the domain name for the GATC cookies. If not set its the website domain, with the www. prefix removed.:user_id - defines a proc to set the userId. Ex: user_id: lambda { |env| env['rack.session']['user_id'] } would return the user_id from the session.:link_attribution - Enables Enhanced Link Attribution.:allow_display_features - Can be used to disable Display Features.:custom_map - Used to Configure and send custom dimensions:optimize_id - Used to Deploy Optimize using gtag:set - Used in the set command to configure multiple propertiesGoogle Global Site tag allows configuring multiple trackers. Use the tracker option to configure the ids:
config.middleware.use(Rack::Tracker) do
handler :google_global, { trackers: [ { id: 'U-XXXXX-Y' }, { id: 'U-WWWWWW-Z'} ] }
end: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.:cookie_domain - sets the domain name for the GATC cookies. If not set its the website domain, with the www. prefix removed.:user_id - defines a proc to set the userId. Ex: user_id: lambda { |env| env['rack.session']['user_id'] } would return the user_id from the session.: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:adjusted_bounce_rate_timeouts - An array of times in seconds that the tracker will use to set timeouts for adjusted bounce rate tracking. See http://analytics.blogspot.ca/2012/07/tracking-adjusted-bounce-rate-in-google.html for details.:enhanced_link_attribution - Enables Enhanced Link Attribution.:advertising - Enables Display Features.:ecommerce - Enables Ecommerce Tracking.:enhanced_ecommerce - Enables Enhanced Ecommerce Tracking:optimize - pass Google Optimize container ID as value (e.g. optimize: 'GTM-1234').:pageview_url_script - a String containing a custom js script evaluating to the url that shoudl be given to the pageview event. Default to window.location.pathname + window.location.search.:explicit_pageview - A boolean that controls whether to send the pageview event on pageload. This defaults to true.To issue Events from the server side just call the tracker method in your controller.
def show
tracker do |t|
t.google_analytics :send, { type: 'event', category: 'button', action: 'click', label: 'nav-buttons', value: 'X' }
end
endIt will render the following to the site source:
ga('send', { 'hitType': 'event', 'eventCategory': 'button', 'eventAction': 'click', 'eventLabel': 'nav-buttons', 'value': 'X' })You can set parameters in your controller too:
def show
tracker do |t|
t.google_analytics :parameter, { dimension1: 'pink' }
end
endWill render this:
ga('set', 'dimension1', 'pink');You can set parameters in your controller:
def show
tracker do |t|
t.google_analytics :enhanced_ecommerce, {
type: 'addItem',
id: '1234',
name: 'Fluffy Pink Bunnies',
sku: 'DD23444',
category: 'Party Toys',
price: '11.99',
quantity: '1'
}
end
endWill render this:
ga("ec:addItem", {"id": "1234", "name": "Fluffy Pink Bunnies", "sku": "DD23444", "category": "Party Toys", "price": "11.99", "quantity": "1"});You can even trigger ecommerce directly from within your controller:
def show
tracker do |t|
t.google_analytics :ecommerce, { type: 'addItem', id: '1234', affiliation: 'Acme Clothing', revenue: '11.99', shipping: '5', tax: '1.29' }
end
endWill give you this:
ga('ecommerce:addItem', { 'id': '1234', 'affiliation': 'Acme Clothing', 'revenue': '11.99', 'shipping': '5', 'tax': '1.29' })To load the ecommerce-plugin, add some configuration to the middleware initialization.
This is not needed for the above to work, but recommened, so you don't have to
take care of the plugin on your own.
config.middleware.use(Rack::Tracker) do
handler :google_analytics, { tracker: 'U-XXXXX-Y', ecommerce: true }
endYou can configure the handler with default options:
config.middleware.use(Rack::Tracker) do
handler :google_adwords_conversion, { id: 123456,
language: "en",
format: "3",
color: "ffffff",
label: "Conversion label",
currency: "USD" }
endTo track adwords conversion from the server side just call the tracker method in your controller.
def show
tracker do |t|
t.google_adwords_conversion :conversion, { value: 10.0 }
end
endYou can also specify a different value from default options:
def show
tracker do |t|
t.google_adwords_conversion :conversion, { id: 123456,
language: 'en',
format: '3',
color: 'ffffff',
label: 'Conversion Label',
value: 10.0 }
end
endGoogle Tag manager code snippet supports the container id
config.middleware.use(Rack::Tracker) do
handler :google_tag_manager, { container: 'GTM-XXXXXX' }
endYou can also use an experimental feature to track pageviews under turbolinks, which adds a pageView event with a virtualUrl of the current url.
config.middleware.use(Rack::Tracker) do
handler :google_tag_manager, { container: 'GTM-XXXXXX', turbolinks: true }
endGTM supports a dataLayer for pushing events as well as variables.
To add events or variables to the dataLayer from the server side, just call the tracker method in your controller.
def show
tracker do |t|
t.google_tag_manager :push, { price: 'X', another_variable: ['array', 'values'] }
end
endFacebook Pixel - adds the Facebook PixelUse in conjunction with the
No open issues yet, or sync has not completed.