Search

Enter a search word or two and press return to see the search results.

Who am I?

Hi, I’m Graeme and these are my notes, from my messy desk. I started this blog because Google proved to be more useful at finding content than anything else I’ve used.

So I started adding my own content in the hopes that Google would index it and allow me to find things again in the future.

It works.

You can find out more about me here, and you should follow me on Twitter here.

Keeping up

You can automatically receive new content here by subscribing to the “Blog RSS” (link below). This is the easiest way to keep up with what I write here.  See this BBC article for a good introduction on RSS and keeping up with the goings on of the Internet more easily.

« Plugs and plugins | Main | Automating creation of a new plugin »
Tuesday
May092006

Google Analytics Plugin

(AKA 'my first plugin')

Since the existing one from the [Plugins](http://wiki.rubyonrails.com/rails/pages/Plugins) page on the rails wiki isn't resolving correctly, I've created my own [Google Analytics](http://www.google.com/analytics/) plugin. I got fed up adding the same chunk of code to `app/views/layouts/application.rhtml` for every new application. So hopefully this will make things nice and easy.

To install it, add my plugin repository to your rails plugin sources:

script/plugin source http://svn.rubaidh.com/plugins/trunk

and to install the Google Analytics plugin:

script/plugin install google_analytics

To configure it, add the following to `config/environment.rb`:

Rubaidh::GoogleAnalytics.tracker_id = 'UA-12345-67'

where the `tracker_id` is what `_uacct` gets set to in the chunk of javascript that Google gives you to insert. That's it! All configured! Your tracking information will be inserted into every page. If you don't want it in particular controller, you can do the usual to skip after_filters:

skip_after_filter :add_google_analytics_code

Simple, eh?

**Update 2006/05/10** I've updated plugin so that it should automatically use the SSL version of the Google Analytics URL if it's on an SSL page (so that you don't get warnings about a mixture of secure and insecure content on a page). I've also added support for specifying the `_udn` which you'll want to put in if you have multiple subdomains appearing on the same report.

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments (9)

Hi. Looks like just the thing, but unfortunately it's keeling over at startup for me :0((. I'm using rails 1.2.3 and it does the same thing in either production of development mode ...

** Starting Rails with development environment...
Exiting
/usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/active_support/dependencies.rb:266:in load_missing_constant': uninitialized constant Rubaidh (NameError)
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/active_support/dependencies.rb:452:in
const_missing'
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/active_support/dependencies.rb:464:in const_missing'
from /Users/attila/src/trunk/config/environment.rb:115
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in
gem_original_require'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in require'
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/active_support/dependencies.rb:495:in
require'
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/active_support/dependencies.rb:342:in new_constants_in'
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/active_support/dependencies.rb:495:in
require'
... 21 levels...
from /usr/local/lib/ruby/gems/1.8/gems/rails-1.2.3/lib/commands/server.rb:39
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in gem_original_require'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in
require'
from script/server:3

Any ideas ?. Would be nice to use if I can get past this little hickup :0).

Thanks.

November 29, 2007 | Unregistered CommenterAttila

Hi,
How can I test google analytics at the development stage ? In Rubaidh::GoogleAnalytics.domain_name = 'example.com', what should be the domain name in the development environment ?

January 28, 2008 | Unregistered CommenterRohan

Is there any chance of this plugin being update to reflect the recent code changes to the GA code snippets?

As reported here: http://www.niallkennedy.com/blog/2008/01/google-analytics-ga-js.html

February 4, 2008 | Unregistered CommenterMarston A.

Nice work! I'd be interested in seeing a GA plugin that could handle goals too. Like a snippet you could add to a controller that was part of a goal.

March 18, 2008 | Unregistered CommenterBrian

Hi,

I've took the liberty to modify your plugin so that it will also track ajax calls and check the content type of the response.

Here it is:

module Rubaidh # :nodoc:
module GoogleAnalyticsMixin
def google_analytics_code(request = nil, headers = nil, flash = nil)
return unless GoogleAnalytics.enabled?
GoogleAnalytics.google_analytics_code(request, headers, flash)
end

# An after_filter to automatically add the analytics code.
def add_google_analytics_code
if response.body.index("</body>")
code = google_analytics_code(request)
response.body.gsub! '</body>', code + '</body>' if response.body.respond_to?(:gsub!) && !code.nil?
elsif response.body.is_a? String # if an Ajax call there won't be a body tag
code = google_analytics_code(request, headers, flash)
response.body << code unless code.nil?
end
end

# A before_filter to automatically store the last accessed url in a cookie
# so it can be retrieved form JavaScript to send it back to google when an
# Ajax call was made.
def add_google_analytics_url
options = { :controller => self.controller_name(), :action => self.action_name(), :only_path => true }.merge(params)
flash[:urchin] = "\"#{url_for(options)}\""
end

end

class GoogleAnalytics
# Specify the Google Analytics ID for this web site. This can be found
# as the value of +_uacct+ in the Javascript excerpt
@@tracker_id = nil
cattr_accessor :tracker_id

# Specify a different domain name from the default.  You'll want to use
# this if you have several subdomains that you want to combine into
# one report. See the Google Analytics documentation for more
# information.
@@domain_name = nil
cattr_accessor :domain_name

# I can't see why you'd want to do this, but you can always change the
# analytics URL.
@@analytics_url = 'http://www.google-analytics.com/urchin.js'
cattr_accessor :analytics_url

# I can't see why you'd want to do this, but you can always change the
# analytics URL (ssl version).
@@analytics_ssl_url = 'https://ssl.google-analytics.com/urchin.js'
cattr_accessor :analytics_ssl_url

# The environments in which to enable the Google Analytics code. Defaults
# to 'production' only.
@@environments = ['development','test','production']
cattr_accessor :environments

# Return true if the Google Analytics system is enabled and configured
# correctly.
def self.enabled?
(environments.include?(RAILS_ENV) and
not tracker_id.blank? and
not analytics_url.blank?)
end

def self.google_analytics_code(request = nil, headers = nil, flash = nil)
extra_code = domain_name.blank? ? nil : "_udn = \"#{domain_name}\";\n"
url = (not request.blank? and request.ssl?) ? analytics_ssl_url : analytics_url
path = "'#{path}'" unless path.nil?
code = "try {\n_uacct = \"#{tracker_id}\";\n#{extra_code}urchinTracker(#{flash ? flash[:urchin] : nil});}\ncatch(e) {}"
# OK, I'm not very bright -- I tried to turn this into a partial and
# failed miserably! So it'll have to live here for now.
if headers && headers["Content-Type"].to_s.index("javascript")
# if content is javascript only (e.g. RJS), just append the javascript code without the html tags
return code
elsif headers.nil? || (headers["Content-Type"].nil? || headers["Content-Type"].to_s === "text/html")
# if content is blank or html, append the javascript code with the html tags
return <<-HTML
<script src="#{url}" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
#{code}
//]]>
</script>
HTML
end
end

end
end

May 21, 2008 | Unregistered CommenterDavid Blain

Hi,

This url is not working. I am not able to download this plugin.

Thanks & Regards
Ganesh Mohan

November 3, 2008 | Unregistered CommenterGanesh Mohan

Hi,

This url is not working. I am not able to download this plugin.

November 3, 2008 | Unregistered CommenterGanesh Mohan

I wrote a small script for myself a while ago that does something like this. Feel free to check it out. http://github.com/djanowski/google_services

November 11, 2008 | Unregistered CommenterDamian Janowski

Can I add a read-only user to my analytics profile via RoR?

Regards

Ajit

December 21, 2009 | Unregistered Commenterajit singh

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>