Class: Rubaidh::GoogleAnalytics

Inherits:
Object
  • Object
show all
Defined in:
lib/rubaidh/google_analytics.rb

Overview

The core functionality to connect a Rails application to a Google Analytics installation.

Constant Summary collapse

@@custom_vars =
{ }
@@tracker_id =
nil
@@domain_name =
nil
@@legacy_mode =
false
@@asynchronous_mode =
false
@@analytics_url =
'http://www.google-analytics.com/urchin.js'
@@analytics_ssl_url =
'https://ssl.google-analytics.com/urchin.js'
@@environments =
['production']
@@formats =
[:html, :all]
@@defer_load =
true
@@local_javascript =
false

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.asynchronous_google_analytics_codeObject

Construct the new asynchronous version of the Google Analytics code.



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/rubaidh/google_analytics.rb', line 268

def self.asynchronous_google_analytics_code
  if !override_domain_name.blank?
    domain_code = "_gaq.push(['_setDomainName', '#{override_domain_name}']);"
    self.override_domain_name = nil
  elsif !domain_name.blank?
    domain_code = "_gaq.push(['_setDomainName', '#{domain_name}']);"
  else
    domain_code = nil
  end
    
  custom_vars = []
  @@custom_vars.each do |name, var|
    custom_vars << "_gaq.push(['_setCustomVar', '#{name}', '#{var[:value]}', #{var[:scope]}]);"
  end

  code = <<-HTML
  <script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', '#{request_tracker_id}']);
    #{domain_code}
    #{custom_vars.empty? ? nil : custom_vars.join("\n")}
    _gaq.push(['_trackPageview(#{request_tracked_path})']);
    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
    })();
  </script>
  HTML
end

.clear_all_custom_varsObject

:singleton-method Clear all custom variables currently set



51
52
53
# File 'lib/rubaidh/google_analytics.rb', line 51

def self.clear_all_custom_vars()
  @@custom_vars = { }
end

.clear_custom_var(name) ⇒ Object

:singleton-method Clear the custom variable specified



58
59
60
# File 'lib/rubaidh/google_analytics.rb', line 58

def self.clear_custom_var(name)
  @@custom_vars[name].delete
end

.enabled?(format) ⇒ Boolean

Return true if the Google Analytics system is enabled and configured correctly for the specified format

Returns:

  • (Boolean)

Raises:



181
182
183
184
# File 'lib/rubaidh/google_analytics.rb', line 181

def self.enabled?(format)
  raise Rubaidh::GoogleAnalyticsConfigurationError if tracker_id.blank? || analytics_url.blank?
  environments.include?(RAILS_ENV) && formats.include?(format.to_sym)
end

.google_analytics_code(ssl = false) ⇒ Object

Construct the javascript code to be inserted on the calling page. The ssl parameter can be used to force the SSL version of the code in legacy mode only.



188
189
190
191
192
193
194
195
196
197
198
# File 'lib/rubaidh/google_analytics.rb', line 188

def self.google_analytics_code(ssl = false)
  if asynchronous_mode
    code = asynchronous_google_analytics_code
  elsif legacy_mode
    code = legacy_google_analytics_code(ssl)
  else
    code = synchronous_google_analytics_code
  end
  
  return code
end

.legacy_analytics_js_url(ssl = false) ⇒ Object

Generate the correct URL for the legacy Analytics JS file



300
301
302
303
304
305
306
# File 'lib/rubaidh/google_analytics.rb', line 300

def self.legacy_analytics_js_url(ssl = false)
  if local_javascript
    LocalAssetTagHelper.new.javascript_path( 'urchin.js' )
  else
    ssl ? analytics_ssl_url : analytics_url
  end
end

.legacy_google_analytics_code(ssl = false) ⇒ Object

Construct the legacy version of the Google Analytics code. The ssl parameter specifies whether or not to return the SSL version of the code.



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/rubaidh/google_analytics.rb', line 202

def self.legacy_google_analytics_code(ssl = false)
  extra_code = domain_name.blank? ? nil : "_udn = \"#{domain_name}\";"
  if !override_domain_name.blank?
    extra_code = "_udn = \"#{override_domain_name}\";"
    self.override_domain_name = nil
  end

  url = legacy_analytics_js_url(ssl)

  code = <<-HTML
  <script src="#{url}" type="text/javascript">
  </script>
  <script type="text/javascript">
  _uacct = "#{request_tracker_id}";
  #{extra_code}
  urchinTracker(#{request_tracked_path});
  </script>
  HTML
end

.request_tracked_pathObject

Determine the path to report for this request



316
317
318
319
320
# File 'lib/rubaidh/google_analytics.rb', line 316

def self.request_tracked_path
  use_tracked_path = override_trackpageview.blank? ? '' : "'#{override_trackpageview}'"
  self.override_trackpageview = nil
  use_tracked_path
end

.request_tracker_idObject

Determine the tracker ID for this request



309
310
311
312
313
# File 'lib/rubaidh/google_analytics.rb', line 309

def self.request_tracker_id
  use_tracker_id = override_tracker_id.blank? ? tracker_id : override_tracker_id
  self.override_tracker_id = nil
  use_tracker_id
end

.set_custom_var(name, value, slot = 1, scope = 3) ⇒ Object

:singleton-method Specify a custom variable to include in the analytics javascript name: variable name value: variable value slot: variable slot (1,2,3,4, or 5) scope: variable scope (page => 3, sesion => 2, visitor => 1)



44
45
46
# File 'lib/rubaidh/google_analytics.rb', line 44

def self.set_custom_var(name, value, slot = 1, scope = 3)
  @@custom_vars[name] = { :value => value, :slot => slot, :scope => scope }
end

.synchronous_google_analytics_codeObject

Construct the synchronous version of the Google Analytics code.



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/rubaidh/google_analytics.rb', line 223

def self.synchronous_google_analytics_code
  if !override_domain_name.blank?
    domain_code = "pageTracker._setDomainName(\"#{override_domain_name}\");"
    self.override_domain_name = nil
  elsif !domain_name.blank?
    domain_code = "pageTracker._setDomainName(\"#{domain_name}\");"
  else
    domain_code = nil
  end
  
  custom_vars = []
  @@custom_vars.each do |name, var|
    custom_vars << "pageTracker._setCustomVar(#{var[:slot]}, \"#{name}\", \"#{var[:value]}\", #{var[:scope]});"
  end
  
  if local_javascript
    code = <<-HTML
    <script src="#{LocalAssetTagHelper.new.javascript_path( 'ga.js' )}" type="text/javascript">
    </script>
    HTML
  else
    code = <<-HTML
    <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>
    HTML
  end
  
  code << <<-HTML
  <script type="text/javascript">
    <!--//--><![CDATA[//><!--
      try {
        var pageTracker = _gat._getTracker('#{request_tracker_id}');
        #{domain_code}
        pageTracker._initData();
        #{custom_vars.empty? ? nil : custom_vars.join("\n")}
        pageTracker._trackPageview(#{request_tracked_path});
      } catch(err) {}
    //--><!]]>
  </script>
  HTML
end

Instance Method Details

#analytics_ssl_urlObject

:singleton-method: The URL that analytics information is sent to when using SSL. This defaults to the standard Google Analytics URL, and you’re unlikely to need to change it. This has no effect unless you’re in legacy mode.



110
# File 'lib/rubaidh/google_analytics.rb', line 110

cattr_accessor :analytics_ssl_url

#analytics_urlObject

:singleton-method: The URL that analytics information is sent to. This defaults to the standard Google Analytics URL, and you’re unlikely to need to change it. This has no effect unless you’re in legacy mode.



102
# File 'lib/rubaidh/google_analytics.rb', line 102

cattr_accessor :analytics_url

#asynchronous_modeObject

:singleton-method: Specify whether the new Asynchronous Google Analytics code should be used. By default, the synchronous Google Analytics code is used. For more information: code.google.com/apis/analytics/docs/tracking/asyncTracking.html



94
# File 'lib/rubaidh/google_analytics.rb', line 94

cattr_accessor :asynchronous_mode

#defer_loadObject

:singleton-method: Set this to true (the default) if you want to load the Analytics javascript at the bottom of page. Set this to false if you want to load the Analytics javascript at the top of the page. The page will render faster if you set this to true, but that will break the linking functions in Rubaidh::GoogleAnalyticsViewHelper.



135
# File 'lib/rubaidh/google_analytics.rb', line 135

cattr_accessor :defer_load

#domain_nameObject

:singleton-method: 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.



78
# File 'lib/rubaidh/google_analytics.rb', line 78

cattr_accessor :domain_name

#environmentsObject

:singleton-method: The environments in which to enable the Google Analytics code. Defaults to ‘production’ only. Supply an array of environment names to change this.



117
# File 'lib/rubaidh/google_analytics.rb', line 117

cattr_accessor :environments

#formatsObject

:singleton-method: The request formats where tracking code should be added. Defaults to [:html, :all]. The entry for :all is necessary to make Google recognize that tracking is installed on a site; it is not the same as responding to all requests. Supply an array of formats to change this.



126
# File 'lib/rubaidh/google_analytics.rb', line 126

cattr_accessor :formats

#legacy_modeObject

:singleton-method: Specify whether the legacy Google Analytics code should be used. By default, the new Google Analytics code is used.



85
# File 'lib/rubaidh/google_analytics.rb', line 85

cattr_accessor :legacy_mode

#local_javascriptObject

:singleton-method: Set this to true to use a local copy of the ga.js (or urchin.js) file. This gives you the added benefit of serving the JS directly from your server, which in case of a big geographical difference between your server and Google’s can speed things up for your visitors. Use the ‘google_analytics:update’ rake task to update the local JS copies.



145
# File 'lib/rubaidh/google_analytics.rb', line 145

cattr_accessor :local_javascript

#override_domain_nameObject

:singleton-method: Set this to override the initialized domain name for a single render. Useful when you’re serving to multiple hosts from a single codebase. Typically you’d set up a before filter in the appropriate controller:

 before_filter :override_domain_name
 def override_domain_name
   Rubaidh::GoogleAnalytics.override_domain_name  = 'foo.com'
end


156
# File 'lib/rubaidh/google_analytics.rb', line 156

cattr_accessor :override_domain_name

#override_tracker_idObject

:singleton-method: Set this to override the initialized tracker ID for a single render. Useful when you’re serving to multiple hosts from a single codebase. Typically you’d set up a before filter in the appropriate controller:

 before_filter :override_tracker_id
 def override_tracker_id
   Rubaidh::GoogleAnalytics.override_tracker_id  = 'UA-123456-7'
end


167
# File 'lib/rubaidh/google_analytics.rb', line 167

cattr_accessor :override_tracker_id

#override_trackpageviewObject

:singleton-method: Set this to override the automatically generated path to the page in the Google Analytics reports for a single render. Typically you’d set this up on an action-by-action basis:

def show
  Rubaidh::GoogleAnalytics.override_trackpageview = "path_to_report"
  ...


177
# File 'lib/rubaidh/google_analytics.rb', line 177

cattr_accessor :override_trackpageview

#tracker_idObject

:singleton-method: Specify the Google Analytics ID for this web site. This can be found as the value of _getTracker if you are using the new (ga.js) tracking code, or the value of _uacct if you are using the old (urchin.js) tracking code.



69
# File 'lib/rubaidh/google_analytics.rb', line 69

cattr_accessor :tracker_id