Create a gist now

Instantly share code, notes, and snippets.

anonymous /gist:14120
Created Oct 1, 2008

require 'net/http'
class GoogleAnalytics
BASE_URL = "http://www.google-analytics.com/__utm.gif?"
def self.create_url(request, options)
params = {}
raise(ArgumentError, "Can't create GA URL without an urchin code") unless params[:utmac] = options.delete(:ga_code)
raise(ArgumentError, "Can't create GA URL without a page URI") unless params[:utmp] = options.delete(:page_uri)
utmdt = options.delete(:description) || "-" # page description
params[:utmdt] = CGI.escape(utmdt)
params[:utmhn] = request.host # domain request is served from
params[:utmr] = request.env['HTTP_REFERER'] || "-" # referring URL
params[:utmv] = "4.3" # tracking code version
params[:utml] = "en-us" # browser language (or could be pulled from user-agent)
params[:utmsc] = "UTF-8" # language encoding (or could be pulled from user-agent)
params[:utmsc] = options.delete(:color_depth) || "-" # browser screen color depth
params[:utmsr] = options.delete(:resolution) || "-" # browser screen resolution
java_enabled = options.delete(:java_enabled)
params[:utmje] = java_enabled ? "1" : "0" # browser supports java
params[:utmfl] = options.delete(:flash_version) || "-" # Flash version
params[:utmn] = rand(8999999999) + 1000000000 # random request number
params[:utmhid] = rand(8999999999) + 1000000000 # random request number
params[:utmcn] = 1 # start new campaign session
user_id = options[:user_id] ? 1000000000 + options.delete(:user_id).to_i : rand(8999999999) + 1000000000
random_utma = rand(1147483647) + 1000000000 # random number for utma
time = Time.now.to_i
utmcc = "__utma=#{user_id}.#{random_utma}.#{time}.#{time}.#{time}.1;+__utmz=#{user_id}.#{time}.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);"
(utmcc += "+__utmv=#{user_id}." + options.map{|k,v| "#{k}=#{v}"}.join("+") + ";") unless options.empty?
params[:utmcc] = CGI.escape(utmcc)
url = BASE_URL + params.map{|k,v| "#{k}=#{v}"}.join("&")
headers = {
'Accept-language' => request.env['HTTP_ACCEPT_LANGUAGE'],
'User-agent' => request.env['HTTP_USER_AGENT']
}
{:url => url, :headers => headers}
end
def self.call(request, options = {})
ga_url = GoogleAnalytics.create_url(request, options)
if RAILS_ENV == 'production'
begin
url = URI.parse(ga_url[:url])
Net::HTTP.start(url.host, url.port) do |http|
http.get("#{url.path}?#{url.query}", ga_url[:headers])
end
rescue
end
end
ga_url
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment