Google Analytics and Rails3 - No Fluff Just Stuff

Google Analytics and Rails3

Posted by: David Bock on December 18, 2010

You just want to get a simple google analytics tracker in your rails 3 application, and you start to research. You get your analytics account set up, and you think you might just stick the javascript google gives you into your application layout file. But then you find article after article, a time-honored plugin/gem, and a couple of pieces of rack middleware that all seem to suggest different ways to do it. You start to feel like an Archaeologist going through the history of rails versions, and you just want to get this working so you can deploy and go home, right?

Right. Here's the simple, modern way to set up Google Analytics with your Rails3 app:

In your Gemfile, add this:

group :production do
  gem 'rack-google_analytics', :require => "rack/google_analytics"
end

and then bundle install.

in your config/application.rb, add this inside the application class definition:

if Rails.env == "production"
  config.middleware.use("Rack::GoogleAnalytics", :web_property_id => "UA-0000000-1")
end

and set that web_property_id to the urchin id that google analytics gives you.

Deploy, and watch the cool stats come into your analytics dashboard.

This is using the rack-google_analytics gem from Jason Perry, installing it as a piece of Rails middleware (as opposed to putting it directly in the config.ru file), and with a little bit of specificity to only hook it up when you are in your production environment.

David Bock

About David Bock

David Bock is a Principal Consultant at CodeSherpas, a company he founded in 2007. Mr. Bock is also the President of the Northern Virginia Java Users Group, the Editor of O'Reilly's OnJava.com website, and a frequent speaker on technology in venues such as the No Fluff Just Stuff Software Symposiums.

In January 2006, Mr. Bock was honored by being awarded the title of Java Champion by a panel of esteemed leaders in the Java Community in a program sponsored by Sun. There are approximately 100 active Java Champions worldwide.

David has also served on several JCP panels, including the Specification of the Java 6 Platform and the upcoming Java Module System.

In addition to his public speaking and training activities, Mr. Bock actively consults as a software engineer, project manager, and team mentor for commercial and government clients.

Why Attend the NFJS Tour?

  • » Cutting-Edge Technologies
  • » Agile Practices
  • » Peer Exchange

Current Topics:

  • Languages on the JVM: Scala, Groovy, Clojure
  • Enterprise Java
  • Core Java, Java 8
  • Agility
  • Testing: Geb, Spock, Easyb
  • REST
  • NoSQL: MongoDB, Cassandra
  • Hadoop
  • Spring 4
  • Cloud
  • Automation Tools: Gradle, Git, Jenkins, Sonar
  • HTML5, CSS3, AngularJS, jQuery, Usability
  • Mobile Apps - iPhone and Android
  • More...
Learn More »