Skip to content

Instantly share code, notes, and snippets.

@panterch
Created June 14, 2013 19:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panterch/5784771 to your computer and use it in GitHub Desktop.
Save panterch/5784771 to your computer and use it in GitHub Desktop.
Simple Google Analytics Measurement Protocol Rails Integration
# -*- encoding : utf-8 -*-
require 'net/http'
class Ga
attr_accessor :user, :category, :action
# target for trackings in test environment
TRACKINGS = []
def initialize(user, category, action)
@user = user
@category = category
@action = action
# user may not yet be persisted and not yet have a uuid
@user.ensure_uuid
end
# see
# https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
def track_uri
uri = URI('http://www.google-analytics.com/collect')
params = {
# The protocol version. The value should be 1.
:v => 1,
# The ID that distinguishes to which Google Analytics property to send data.
:tid => 'UA-XXXXXX-1',
# An ID unique to a particular visitor / user.
:cid => @user.uuid,
# The type of interaction collected for a particular user.
:t => 'event',
# Specifies the event category
:ec => @category,
# Specifies the event action
:ea => @action
}
uri.query = URI.encode_www_form(params)
uri
end
def track
if 'production' == Rails.env
logger.info("Track: #{self.track_uri}")
Net::HTTP.get(self.track_uri)
elsif 'test' == Rails.env
TRACKINGS << self.track_uri.to_s
else
logger.info("Would track: #{self.track_uri}")
end
end
def logger
Rails.logger
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment