Reputation: 81
I want to implement this new method of Google Analytics, I want to conditinally insert this code in the head section conditionally in production mode only, any suggestion to how to do this?
http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html
Upvotes: 6
Views: 4734
Reputation: 171
I know this is already answered, but I spent quite a bit of time based on an answer above which seems to be outdated. So I am posting what I did to get Google Analytics working with my Rails 3.0 app.
1) Add the following in your Gemfile
group :production do
gem 'rack-google-analytics', :require => 'rack/google-analytics'
end
Note that it is rack-google-analytics and NOT rack-google_analytics. Ditto with the require part
2) In your config/environments/production.rb file, add the following snippet (replacing the dummy tracker with the google analytics tracker for your website).
config.gem 'rack-google-analytics', :lib => 'rack/google-analytics'
config.middleware.use Rack::GoogleAnalytics, :tracker => 'UA-XXXXXXXX-X'
3) Run bundle install and start the rails server
4) Sit back and see the analytics flowing in!
Check out https://github.com/leehambley/rack-google-analytics/blob/master/README.md for instructions on how to make it work with sinatra, padrino etc.
Also, the latest copy of the gem uses :async
option to use asynchronous tracker. The default is true, so you won't need to use this option unless you want to suppress async for some strange reason!
Upvotes: 11
Reputation: 5511
For people coming across this article, be aware this gem supports the traditional google analytics (as opposed to the "newer" aysnc version). Google Analytics Async
I didn't really see any switches to convert between the 2 types.
Upvotes: 1
Reputation: 950
Google Analytics and Rails in 5 EASY Steps:
If you are in Rails 3, I just found a great solution for doing Google Analytics in Rails apps.
(1) In your Gemfile:
group :production do
gem 'rack-google_analytics', :require => "rack/google_analytics"
end
(2) Bundle Install
(3) In your config/application.rb (put this in the class definition section - careful not to drop it in a module. I put mine right under "class Application"):
if Rails.env == "production"
config.middleware.use("Rack::GoogleAnalytics", :web_property_id => "UA-0000000-1")
end
(4) Initiate your Google Analytics account
(5) Copy and paste that funky web_property_id from Google's supplied code into the code from (3), replacing 'UA-000000-1'
That's it!
I originally found this solution here: David Bock Article
Upvotes: 11
Reputation: 1569
Are you using Rails 2.3 ? You could wrap the snip in an if statement,
<% if Rails.env.production? %>
<!-- my analytics code -->
<% end %>
simple enough.
Upvotes: 7