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 startet we're shipping support for the following services out of the box:
Add this line to your application's Gemfile:
gem 'rack-tracker'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rack-tracker
Add 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.
: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. Defaults toauto.: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.
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 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}
endcustom_audience- adds the Custom audience segmentation pixel
To track Conversions from the server side just call the tracker method in your controller.
def show
tracker do |t|
t.facebook :track, { id: '123456789', value: 1, currency: 'EUR' }
end
endWill result in the following:
window._fbq.push(["track", "123456789", {'value': 1, 'currency': 'EUR'}]);Just integrate the handler with your matching account_id and you will be ready to go
use Rack::Tracker do
handler :vwo, { account_id: 'YOUR_ACCOUNT_ID' }
endTo enable GoSquared tracking:
config.middleware.use(Rack::Tracker) do
handler :go_squared, { tracker: 'ABCDEFGH' }
endThis will add the tracker to the page like so:
_gs('ABCDEFGH');You can also set multiple named trackers if need be:
config.middleware.use(Rack::Tracker) do
handler :go_squared, {
trackers: {
primaryTracker: 'ABCDEFGH',
secondaryTracker: '1234567',
}
}
endThis will add the specified trackers to the page like so:
_gs('ABCDEFGH', 'primaryTracker');
_gs('1234567', 'secondaryTracker');You can set a variety of options by passing the following settings. If you don't set any of the following options, they will be omitted from the rendered code.
:anonymize_ip:cookie_domain:use_cookies:track_hash:track_local:track_params
To track the visitor name from the server side, just call the tracker method in your controller.
def show
tracker do |t|
t.go_squared :visitor_name, { name: 'John Doe' }
end
endIt will render the following to the site source:
_gs("set", "visitorName", "John Doe");To track visitor properties from the server side, just call the tracker method in your controller.
def show
tracker do |t|
t.go_squared :visitor_info, { age: 35, favorite_food: 'pizza' }
end
endIt will render the following to the site source:
_gs("set", "visitor", { "age": 35, "favorite_food": "pizza" });Tough we give you handlers for a few tracking services right out of the box, you might be interested adding support for your custom tracking/analytics service.
Writing a handler is straight forward ;) and there are just a couple of methods that your class needs to implement.
Start with a plain ruby class that inherits from Rack::Tracker::Handler
class MyHandler < Rack::Tracker::Handler
...
endSecond we need a method called #render which will take care of rendering a
template.
def render
Tilt.new( File.join( File.dirname(__FILE__), 'template', 'my_handler.erb') ).render(self)
endThis will render the template/my_handler.erb and inject the result into the source. You
can be creative about where the template is stored, but we tend to have them around
our actual handler code.
<script>
console.log('my tracker: ' + <%= options.to_json %>)
</script>Lets give it a try! We need to mount our new handler in the Rack::Tracker middleware
config.middleware.use(Rack::Tracker) do
handler MyTracker, { awesome: true }
endEverything you're passing to the handler will be available as #options in your
template, so you'll also gain access to the env-hash belonging to the current request.
Run your application and make a request, the result of the above template can be
found right before </head>. You can change the position in your handler-code:
class MyHandler < Rack::Tracker::Handler
self.position = :body
...
endThe snippit will then be rendered right before </body>.
To enable the tracker dsl functionality in your controllers
you need to implement the track class method on your handler:
def self.track(name, *event)
# do something with the event(s) to prepare them for your template
# and return a hash with a signature like { name => event }
endCheckout the existing handlers in lib/rack/tracker for some inspiration. :)
First of all, thank you for your help! 💚
If you want a feature implemented, the best way to get it done is to submit a pull request that implements it. Tests, readme and changelog entries would be nice.
- Fork it ( http://github.com/railslove/rack-tracker/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request