Skip to content

Instantly share code, notes, and snippets.

@zachpendleton
Created May 7, 2010 20:06
Show Gist options
  • Save zachpendleton/393945 to your computer and use it in GitHub Desktop.
Save zachpendleton/393945 to your computer and use it in GitHub Desktop.
Google Analytics Rack
module Rack
class GoogleAnalytics
def initialize(app,id)
@app = app
@id = id
end
def call(env)
status,headers,response = @app.call(env)
response.each do |part|
if part =~ /<\/body>/
# The begin/rescue block is required because this method craps out
# when the static page is stored in memcached and not the file system
begin
part.sub!(/<\/body>/, "#{tracking_code}</body>")
rescue
end
end
end
headers['Content-Length'] = response.length.to_s
[status,headers,response]
end
private
def tracking_code
code = <<-END_CODE
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker(#{@id});
pageTracker._trackPageview();
} catch(err) {}
</script>
END_CODE
code
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment