kyusik-google_analytics 1.1.5

Sign up to get free protection for your applications and to get access to all the features.
data/CREDITS ADDED
@@ -0,0 +1,14 @@
1
+ This plugin was initially release by Graeme Mathieson, of Rubaidh Ltd.
2
+ However, since it appeared on github, it has benefited from the contributions
3
+ of many, including:
4
+
5
+ * Mike Gunderloy (ffmike)
6
+ * Mark Catley (markcatley)
7
+ * Kenneth Kalmer (kennethkalmer)
8
+ * Daniel Morrison (danielmorrison)
9
+
10
+ Thank you to all these folks for their contributions, and thank you also to
11
+ Github for facilitating their contribution without having to wait for me to
12
+ accept patches!
13
+
14
+ If I've missed anybody out, please fork, patch and send me a pull request. :-)
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2006-2008 Rubaidh Ltd.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,140 @@
1
+ = GoogleAnalytics
2
+
3
+ This plugin enables Google Analytics support in your application. By default
4
+ it will output the analytics code for every single page automatically, if it
5
+ is configured correctly. This is done by adding:
6
+
7
+ Rubaidh::GoogleAnalytics.tracker_id = 'UA-12345-67'
8
+
9
+ to your <tt>config/environment.rb</tt>, inserting your own tracker id. This
10
+ can be discovered by looking at the value assigned to +_uacct+ in the
11
+ Javascript code.
12
+
13
+ If you want to disable the code insertion for particular pages, add the
14
+ following to controllers that don't want it:
15
+
16
+ skip_after_filter :add_google_analytics_code
17
+
18
+ If you are running rails 2.1 or above add install this by adding:
19
+
20
+ config.gem 'rubaidh-google_analytics', :lib => 'rubaidh/google_analytics', :source => 'http://gems.github.com'
21
+
22
+ and run:
23
+
24
+ rake gems:install
25
+
26
+ Simple. :-)
27
+
28
+
29
+ == Google Analytics Tracking Code versions
30
+
31
+ This version of the plugin uses the new Google Analytics code (ga.js) by
32
+ default.
33
+
34
+ To use the legacy tracking code add the following line to your
35
+ <tt>config/environment.rb</tt>:
36
+
37
+ Rubaidh::GoogleAnalytics.legacy_mode = true
38
+
39
+ To use new asynchronous tracking code add the following line to your
40
+ <tt>config/environment.rb</tt>:
41
+
42
+ Rubaidh::GoogleAnalytics.asynchronous_mode = true
43
+
44
+ == Tracking custom variables
45
+
46
+ You can track custom variables by setting the variable using:
47
+
48
+ Rubaidh::GoogleAnalytics.set_custom_var(name, value, slot, scope)
49
+
50
+ You can set more than one custom variable at a time by making repeated calls to
51
+ +set_custom_var+ with different variable names.
52
+
53
+ == Tracking outbound Links
54
+
55
+ Google Analytics only tracks intra-site links by default. To create an
56
+ outbound link that is tracked use the link_to_tracked helper:
57
+
58
+ link_to_tracked(name, track_path = "/", options = {}, html_options = {})
59
+
60
+ You can use the track_path parameter to group your outbound links into logical
61
+ folders inside of Google Analytics.
62
+
63
+ The other forms of link_to are also supported:
64
+
65
+ link_to_tracked_if(condition, name, track_path = "/", options = {}, html_options = {}, &block)
66
+ link_to_tracked_unless(condition, name, track_path = "/", options = {}, html_options = {}, &block)
67
+ link_to_tracked_unless_current(name, track_path = "/", options = {}, html_options = {}, &block)
68
+
69
+ To track outbound links, you should set
70
+
71
+ Rubaidh::GoogleAnalytics.defer_load = false
72
+
73
+ This will move the tracking javascript to the top of your page.
74
+ (see http://www.google.com/support/googleanalytics/bin/answer.py?answer=55527&topic=11006)
75
+
76
+ Tracked links respect the legacy_mode flag.
77
+
78
+ Note: Link-tracking works by inserting onclick() code in the HTML. Because of
79
+ this, it will overwrite any onclick that you insert in the html_options hash.
80
+
81
+ == Using local copies of the Analytics Javascript files
82
+
83
+ Under certain circumstances you might find it valuable to serve a copy of the
84
+ Analytics JavaScript directly from your server to your visitors, and not
85
+ directly from Google. If your visitors are geograhically very far from Google,
86
+ or if they have low quality international bandwidth, the loading time for the
87
+ Analytics JS might kill the user experience and force you to remove the
88
+ valuable tracking code from your site.
89
+
90
+ This plugin now supports local copies of the legacy and new Analytics
91
+ JavaScript files, updated via a rake task and served courtesy of the Rails
92
+ AssetTagHelper methods. So even if you use asset hosts, the JS will be served
93
+ from the correct source and under the correct protocol (HTTP/HTTPS).
94
+
95
+ To enable cached copies and the following to your initialization code:
96
+
97
+ Rubaidh::GoogleAnalytics.local_javascript = true
98
+
99
+ Use the following rake task to update the local copy of the JavaScript file:
100
+
101
+ rake google_analytics:updates
102
+
103
+ To keep the file updated you can add the following to your Capistrano
104
+ configuration:
105
+
106
+ after "deploy:symlink", "deploy:google_analytics"
107
+
108
+ namespace :deploy do
109
+ desc "Update local Google Analytics files"
110
+ task :google_analytics, :role => :web do
111
+ run "cd #{current_path} && rake google_analytics:update RAILS_ENV=#{ENV['RAILS_ENV']}"
112
+ end
113
+ end
114
+
115
+ The above Capistrano recipe will almost certainly need some adjustments based
116
+ on how you run your deployments, but you should get the idea.
117
+
118
+ == Overriding application-default values
119
+
120
+ If you're using one Rails application to serve pages across multiple domains,
121
+ you may wish to override the domain and tracker ID values on a
122
+ controller-by-controller or view-by-view basis. You can do this by setting the
123
+ override_domain_name and override_tracker_id properties. These properties are
124
+ automatically reset after each use, so the values you set for domain_name and
125
+ tracker_id (usually in an initializer) will apply to all other requests.
126
+
127
+ before_filter :local_analytics
128
+
129
+ def local_analytics
130
+ Rubaidh::GoogleAnalytics.override_domain_name = 'foo.com'
131
+ Rubaidh::GoogleAnalytics.override_tracker_id = 'UA-123456-7'
132
+ end
133
+
134
+ See the documentation for the GoogleAnalytics class for other configuration
135
+ options.
136
+
137
+ Note: You will need to have the mocha gem installed to run the tests for this
138
+ plugin.
139
+
140
+ Copyright (c) 2006-2008 Rubaidh Ltd, released under the MIT license.
@@ -0,0 +1,56 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+ require 'rake/gempackagetask'
5
+ require 'rcov/rcovtask'
6
+ require 'rubyforge'
7
+
8
+ desc 'Default: run unit tests.'
9
+ task :default => :test
10
+
11
+ task :clean => [:clobber_rdoc, :clobber_package]
12
+
13
+ desc 'Test the google_analytics plugin.'
14
+ Rake::TestTask.new(:test) do |t|
15
+ t.libs << 'lib'
16
+ t.pattern = 'test/**/*_test.rb'
17
+ t.verbose = true
18
+ end
19
+
20
+ Rcov::RcovTask.new do |t|
21
+ t.test_files = FileList["test/**/*_test.rb"]
22
+ t.verbose = true
23
+ t.rcov_opts = ["-x", "^/"]
24
+ end
25
+
26
+ desc 'Generate documentation for the google_analytics plugin.'
27
+ Rake::RDocTask.new(:rdoc) do |rdoc|
28
+ rdoc.rdoc_dir = 'rdoc'
29
+ rdoc.title = 'GoogleAnalytics'
30
+ rdoc.options << '--line-numbers' << '--inline-source'
31
+ rdoc.rdoc_files.include('README.rdoc')
32
+ rdoc.rdoc_files.include('lib/**/*.rb')
33
+ end
34
+
35
+ gem_spec = eval(File.read('google_analytics.gemspec'))
36
+
37
+ Rake::GemPackageTask.new(gem_spec) do |p|
38
+ p.need_tar = false
39
+ p.need_zip = false
40
+ end
41
+
42
+ desc 'Package and upload the release to rubyforge.'
43
+ task :release => [:clean, :package] do |t|
44
+ rubyforge = RubyForge.new.configure
45
+ rubyforge.login
46
+ rubyforge.add_release gem_spec.rubyforge_project, gem_spec.name, gem_spec.version.to_s, "pkg/#{gem_spec.name}-#{gem_spec.version}.gem"
47
+ end
48
+
49
+ begin
50
+ gem 'ci_reporter'
51
+ require 'ci/reporter/rake/test_unit'
52
+ task :bamboo => "ci:setup:testunit"
53
+ rescue LoadError
54
+ end
55
+
56
+ task :bamboo => [ :package, :test ]
@@ -0,0 +1,2 @@
1
+ module Rubaidh #:nodoc:
2
+ end
@@ -0,0 +1,328 @@
1
+ require 'active_support'
2
+ require 'action_pack'
3
+ require 'action_view'
4
+
5
+ module Rubaidh # :nodoc:
6
+ # This module gets mixed in to ActionController::Base
7
+ module GoogleAnalyticsMixin
8
+ # The javascript code to enable Google Analytics on the current page.
9
+ # Normally you won't need to call this directly; the +add_google_analytics_code+
10
+ # after filter will insert it for you.
11
+ def google_analytics_code
12
+ GoogleAnalytics.google_analytics_code(request.ssl?) if GoogleAnalytics.enabled?(request.format)
13
+ end
14
+
15
+ # An after_filter to automatically add the analytics code.
16
+ # If you intend to use the link_to_tracked view helpers, you need to set Rubaidh::GoogleAnalytics.defer_load = false
17
+ # to load the code at the top of the page
18
+ # (see http://www.google.com/support/googleanalytics/bin/answer.py?answer=55527&topic=11006)
19
+ def add_google_analytics_code
20
+ if GoogleAnalytics.asynchronous_mode
21
+ response.body.sub! /<[bB][oO][dD][yY]>/, "<body>#{google_analytics_code}" if response.body.respond_to?(:sub!)
22
+ elsif GoogleAnalytics.defer_load
23
+ response.body.sub! /<\/[bB][oO][dD][yY]>/, "#{google_analytics_code}</body>" if response.body.respond_to?(:sub!)
24
+ else
25
+ response.body.sub! /(<[bB][oO][dD][yY][^>]*>)/, "\\1#{google_analytics_code}" if response.body.respond_to?(:sub!)
26
+ end
27
+ end
28
+ end
29
+
30
+ class GoogleAnalyticsConfigurationError < StandardError; end
31
+
32
+ # The core functionality to connect a Rails application
33
+ # to a Google Analytics installation.
34
+ class GoogleAnalytics
35
+
36
+ @@custom_vars = { }
37
+ ##
38
+ # :singleton-method
39
+ # Specify a custom variable to include in the analytics javascript
40
+ # name: variable name
41
+ # value: variable value
42
+ # slot: variable slot (1,2,3,4, or 5)
43
+ # scope: variable scope (page => 3, sesion => 2, visitor => 1)
44
+ def self.set_custom_var(name, value, slot = 1, scope = 3)
45
+ @@custom_vars[name] = { :value => value, :slot => slot, :scope => scope }
46
+ end
47
+
48
+ ##
49
+ # :singleton-method
50
+ # Clear all custom variables currently set
51
+ def self.clear_all_custom_vars()
52
+ @@custom_vars = { }
53
+ end
54
+
55
+ ##
56
+ # :singleton-method
57
+ # Clear the custom variable specified
58
+ def self.clear_custom_var(name)
59
+ @@custom_vars[name].delete
60
+ end
61
+
62
+ @@tracker_id = nil
63
+ ##
64
+ # :singleton-method:
65
+ # Specify the Google Analytics ID for this web site. This can be found
66
+ # as the value of +_getTracker+ if you are using the new (ga.js) tracking
67
+ # code, or the value of +_uacct+ if you are using the old (urchin.js)
68
+ # tracking code.
69
+ cattr_accessor :tracker_id
70
+
71
+ @@domain_name = nil
72
+ ##
73
+ # :singleton-method:
74
+ # Specify a different domain name from the default. You'll want to use
75
+ # this if you have several subdomains that you want to combine into
76
+ # one report. See the Google Analytics documentation for more
77
+ # information.
78
+ cattr_accessor :domain_name
79
+
80
+ @@legacy_mode = false
81
+ ##
82
+ # :singleton-method:
83
+ # Specify whether the legacy Google Analytics code should be used. By
84
+ # default, the new Google Analytics code is used.
85
+ cattr_accessor :legacy_mode
86
+
87
+ @@asynchronous_mode = false
88
+ ##
89
+ # :singleton-method:
90
+ # Specify whether the new Asynchronous Google Analytics code should be used.
91
+ # By default, the synchronous Google Analytics code is used.
92
+ # For more information:
93
+ # http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html
94
+ cattr_accessor :asynchronous_mode
95
+
96
+ @@analytics_url = 'http://www.google-analytics.com/urchin.js'
97
+ ##
98
+ # :singleton-method:
99
+ # The URL that analytics information is sent to. This defaults to the
100
+ # standard Google Analytics URL, and you're unlikely to need to change it.
101
+ # This has no effect unless you're in legacy mode.
102
+ cattr_accessor :analytics_url
103
+
104
+ @@analytics_ssl_url = 'https://ssl.google-analytics.com/urchin.js'
105
+ ##
106
+ # :singleton-method:
107
+ # The URL that analytics information is sent to when using SSL. This defaults to the
108
+ # standard Google Analytics URL, and you're unlikely to need to change it.
109
+ # This has no effect unless you're in legacy mode.
110
+ cattr_accessor :analytics_ssl_url
111
+
112
+ @@environments = ['production']
113
+ ##
114
+ # :singleton-method:
115
+ # The environments in which to enable the Google Analytics code. Defaults
116
+ # to 'production' only. Supply an array of environment names to change this.
117
+ cattr_accessor :environments
118
+
119
+ @@formats = [:html, :all]
120
+ ##
121
+ # :singleton-method:
122
+ # The request formats where tracking code should be added. Defaults to +[:html, :all]+. The entry for
123
+ # +:all+ is necessary to make Google recognize that tracking is installed on a
124
+ # site; it is not the same as responding to all requests. Supply an array
125
+ # of formats to change this.
126
+ cattr_accessor :formats
127
+
128
+ @@defer_load = true
129
+ ##
130
+ # :singleton-method:
131
+ # Set this to true (the default) if you want to load the Analytics javascript at
132
+ # the bottom of page. Set this to false if you want to load the Analytics
133
+ # javascript at the top of the page. The page will render faster if you set this to
134
+ # true, but that will break the linking functions in Rubaidh::GoogleAnalyticsViewHelper.
135
+ cattr_accessor :defer_load
136
+
137
+ @@local_javascript = false
138
+ ##
139
+ # :singleton-method:
140
+ # Set this to true to use a local copy of the ga.js (or urchin.js) file.
141
+ # This gives you the added benefit of serving the JS directly from your
142
+ # server, which in case of a big geographical difference between your server
143
+ # and Google's can speed things up for your visitors. Use the
144
+ # 'google_analytics:update' rake task to update the local JS copies.
145
+ cattr_accessor :local_javascript
146
+
147
+ ##
148
+ # :singleton-method:
149
+ # Set this to override the initialized domain name for a single render. Useful
150
+ # when you're serving to multiple hosts from a single codebase. Typically you'd
151
+ # set up a before filter in the appropriate controller:
152
+ # before_filter :override_domain_name
153
+ # def override_domain_name
154
+ # Rubaidh::GoogleAnalytics.override_domain_name = 'foo.com'
155
+ # end
156
+ cattr_accessor :override_domain_name
157
+
158
+ ##
159
+ # :singleton-method:
160
+ # Set this to override the initialized tracker ID for a single render. Useful
161
+ # when you're serving to multiple hosts from a single codebase. Typically you'd
162
+ # set up a before filter in the appropriate controller:
163
+ # before_filter :override_tracker_id
164
+ # def override_tracker_id
165
+ # Rubaidh::GoogleAnalytics.override_tracker_id = 'UA-123456-7'
166
+ # end
167
+ cattr_accessor :override_tracker_id
168
+
169
+ ##
170
+ # :singleton-method:
171
+ # Set this to override the automatically generated path to the page in the
172
+ # Google Analytics reports for a single render. Typically you'd set this up on an
173
+ # action-by-action basis:
174
+ # def show
175
+ # Rubaidh::GoogleAnalytics.override_trackpageview = "path_to_report"
176
+ # ...
177
+ cattr_accessor :override_trackpageview
178
+
179
+ # Return true if the Google Analytics system is enabled and configured
180
+ # correctly for the specified format
181
+ def self.enabled?(format)
182
+ raise Rubaidh::GoogleAnalyticsConfigurationError if tracker_id.blank? || analytics_url.blank?
183
+ environments.include?(RAILS_ENV) && formats.include?(format.to_sym)
184
+ end
185
+
186
+ # Construct the javascript code to be inserted on the calling page. The +ssl+
187
+ # parameter can be used to force the SSL version of the code in legacy mode only.
188
+ def self.google_analytics_code(ssl = false)
189
+ if asynchronous_mode
190
+ code = asynchronous_google_analytics_code
191
+ elsif legacy_mode
192
+ code = legacy_google_analytics_code(ssl)
193
+ else
194
+ code = synchronous_google_analytics_code
195
+ end
196
+
197
+ return code
198
+ end
199
+
200
+ # Construct the legacy version of the Google Analytics code. The +ssl+
201
+ # parameter specifies whether or not to return the SSL version of the code.
202
+ def self.legacy_google_analytics_code(ssl = false)
203
+ extra_code = domain_name.blank? ? nil : "_udn = \"#{domain_name}\";"
204
+ if !override_domain_name.blank?
205
+ extra_code = "_udn = \"#{override_domain_name}\";"
206
+ self.override_domain_name = nil
207
+ end
208
+
209
+ url = legacy_analytics_js_url(ssl)
210
+
211
+ code = <<-HTML
212
+ <script src="#{url}" type="text/javascript">
213
+ </script>
214
+ <script type="text/javascript">
215
+ _uacct = "#{request_tracker_id}";
216
+ #{extra_code}
217
+ urchinTracker(#{request_tracked_path});
218
+ </script>
219
+ HTML
220
+ end
221
+
222
+ # Construct the synchronous version of the Google Analytics code.
223
+ def self.synchronous_google_analytics_code
224
+ if !override_domain_name.blank?
225
+ domain_code = "pageTracker._setDomainName(\"#{override_domain_name}\");"
226
+ self.override_domain_name = nil
227
+ elsif !domain_name.blank?
228
+ domain_code = "pageTracker._setDomainName(\"#{domain_name}\");"
229
+ else
230
+ domain_code = nil
231
+ end
232
+
233
+ custom_vars = []
234
+ @@custom_vars.each do |name, var|
235
+ custom_vars << "pageTracker._setCustomVar(#{var[:slot]}, \"#{name}\", \"#{var[:value]}\", #{var[:scope]});"
236
+ end
237
+
238
+ if local_javascript
239
+ code = <<-HTML
240
+ <script src="#{LocalAssetTagHelper.new.javascript_path( 'ga.js' )}" type="text/javascript">
241
+ </script>
242
+ HTML
243
+ else
244
+ code = <<-HTML
245
+ <script type="text/javascript">
246
+ var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
247
+ document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
248
+ </script>
249
+ HTML
250
+ end
251
+
252
+ code << <<-HTML
253
+ <script type="text/javascript">
254
+ <!--//--><![CDATA[//><!--
255
+ try {
256
+ var pageTracker = _gat._getTracker('#{request_tracker_id}');
257
+ #{domain_code}
258
+ pageTracker._initData();
259
+ #{custom_vars.empty? ? nil : custom_vars.join("\n")}
260
+ pageTracker._trackPageview(#{request_tracked_path});
261
+ } catch(err) {}
262
+ //--><!]]>
263
+ </script>
264
+ HTML
265
+ end
266
+
267
+ # Construct the new asynchronous version of the Google Analytics code.
268
+ def self.asynchronous_google_analytics_code
269
+ if !override_domain_name.blank?
270
+ domain_code = "_gaq.push(['_setDomainName', '#{override_domain_name}']);"
271
+ self.override_domain_name = nil
272
+ elsif !domain_name.blank?
273
+ domain_code = "_gaq.push(['_setDomainName', '#{domain_name}']);"
274
+ else
275
+ domain_code = nil
276
+ end
277
+
278
+ custom_vars = []
279
+ @@custom_vars.each do |name, var|
280
+ custom_vars << "_gaq.push(['_setCustomVar', '#{name}', '#{var[:value]}', #{var[:scope]}]);"
281
+ end
282
+
283
+ code = <<-HTML
284
+ <script type="text/javascript">
285
+ var _gaq = _gaq || [];
286
+ _gaq.push(['_setAccount', '#{request_tracker_id}']);
287
+ #{domain_code}
288
+ #{custom_vars.empty? ? nil : custom_vars.join("\n")}
289
+ _gaq.push(['_trackPageview(#{request_tracked_path})']);
290
+ (function() {
291
+ var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
292
+ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
293
+ (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
294
+ })();
295
+ </script>
296
+ HTML
297
+ end
298
+
299
+ # Generate the correct URL for the legacy Analytics JS file
300
+ def self.legacy_analytics_js_url(ssl = false)
301
+ if local_javascript
302
+ LocalAssetTagHelper.new.javascript_path( 'urchin.js' )
303
+ else
304
+ ssl ? analytics_ssl_url : analytics_url
305
+ end
306
+ end
307
+
308
+ # Determine the tracker ID for this request
309
+ def self.request_tracker_id
310
+ use_tracker_id = override_tracker_id.blank? ? tracker_id : override_tracker_id
311
+ self.override_tracker_id = nil
312
+ use_tracker_id
313
+ end
314
+
315
+ # Determine the path to report for this request
316
+ def self.request_tracked_path
317
+ use_tracked_path = override_trackpageview.blank? ? '' : "'#{override_trackpageview}'"
318
+ self.override_trackpageview = nil
319
+ use_tracked_path
320
+ end
321
+
322
+ end
323
+
324
+ class LocalAssetTagHelper # :nodoc:
325
+ # For helping with local javascripts
326
+ include ActionView::Helpers::AssetTagHelper
327
+ end
328
+ end
@@ -0,0 +1,67 @@
1
+ module Rubaidh
2
+ # Collection of methods similar to the ones in ActionView::Helpers::UrlHelper,
3
+ # with the addition of outbound link tracking. See the Google Analytics help
4
+ # at http://www.google.com/support/googleanalytics/bin/answer.py?answer=55527
5
+ # for more information on outbound link tracking.
6
+ module GoogleAnalyticsViewHelper
7
+ # Creates a link tag of the given +name+ using a URL created by the set of +options+,
8
+ # with outbound link tracking under +track_path+ in Google Analytics. The +html_options+
9
+ # will accept a hash of attributes for the link tag.
10
+ def link_to_tracked(name, track_path = "/", options = {}, html_options = {})
11
+ raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true
12
+ html_options.merge!({:onclick => tracking_call(track_path)})
13
+ link_to name, options, html_options
14
+ end
15
+
16
+ # Creates a link tag of the given +name+ using a URL created by the set of +options+
17
+ # if +condition+ is true, with outbound link tracking under +track_path+ in Google Analytics.
18
+ # The +html_options+ will accept a hash of attributes for the link tag.
19
+ def link_to_tracked_if(condition, name, track_path = "/", options = {}, html_options = {}, &block)
20
+ raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true
21
+ html_options.merge!({:onclick => tracking_call(track_path)})
22
+ link_to_unless !condition, name, options, html_options, &block
23
+ end
24
+
25
+ # Creates a link tag of the given +name+ using a URL created by the set of +options+
26
+ # unless +condition+ is true, with outbound link tracking under +track_path+ in Google Analytics.
27
+ # The +html_options+ will accept a hash of attributes for the link tag.
28
+ def link_to_tracked_unless(condition, name, track_path = "/", options = {}, html_options = {}, &block)
29
+ raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true
30
+ html_options.merge!({:onclick => tracking_call(track_path)})
31
+ link_to_unless condition, name, options, html_options, &block
32
+ end
33
+
34
+ # Creates a link tag of the given +name+ using a URL created by the set of +options+
35
+ # unless the current request URI is the same as the link's, with outbound link tracking
36
+ # under +track_path+ in Google Analytics. If the request URI is the same as the link
37
+ # URI, only the name is returned, or the block is yielded, if one exists.
38
+ # The +html_options+ will accept a hash of attributes for the link tag.
39
+ def link_to_tracked_unless_current(name, track_path = "/", options = {}, html_options = {}, &block)
40
+ raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true
41
+ html_options.merge!({:onclick =>tracking_call(track_path)})
42
+ link_to_unless current_page?(options), name, options, html_options, &block
43
+ end
44
+
45
+ private
46
+
47
+ def tracking_call(track_path)
48
+ if GoogleAnalytics.legacy_mode
49
+ "javascript:urchinTracker('#{track_path}');"
50
+ else
51
+ "javascript:pageTracker._trackPageview('#{track_path}');"
52
+ end
53
+ end
54
+
55
+ end
56
+
57
+ # Error raised by tracking methods if Rubaidh::GoogleAnalytics.defer_load is not configured
58
+ # properly to enable tracking.
59
+ class AnalyticsError < StandardError
60
+ attr_reader :message
61
+
62
+ def initialize(message)
63
+ @message = message
64
+ end
65
+ end
66
+ end
67
+
@@ -0,0 +1,5 @@
1
+ require 'rubaidh/google_analytics'
2
+ require 'rubaidh/view_helpers'
3
+ ActionController::Base.send :include, Rubaidh::GoogleAnalyticsMixin
4
+ ActionController::Base.send :after_filter, :add_google_analytics_code
5
+ ActionView::Base.send :include, Rubaidh::GoogleAnalyticsViewHelper
@@ -0,0 +1,62 @@
1
+ namespace :google_analytics do
2
+
3
+ desc "Update the local copy of the Analytics JS"
4
+ task :update => :environment do
5
+ file = Rubaidh::GoogleAnalytics.legacy_mode ? 'urchin.js' : 'ga.js'
6
+ File.open( File.join( RAILS_ROOT, 'public', 'javascripts', file ), 'w+' ) do |f|
7
+ res = Net::HTTP.get_response( 'www.google-analytics.com', '/' + file )
8
+ f.write( res.plain_body )
9
+ end
10
+ end
11
+ end
12
+
13
+ # Intended to extend the Net::HTTP response object
14
+ # and adds support for decoding gzip and deflate encoded pages
15
+ #
16
+ # Author: Jason Stirk <http://griffin.oobleyboo.com>
17
+ # Home: http://griffin.oobleyboo.com/projects/http_encoding_helper
18
+ # Created: 5 September 2007
19
+ # Last Updated: 23 November 2007
20
+ #
21
+ # Usage:
22
+ #
23
+ # require 'net/http'
24
+ # require 'http_encoding_helper'
25
+ # headers={'Accept-Encoding' => 'gzip, deflate' }
26
+ # http = Net::HTTP.new('griffin.oobleyboo.com', 80)
27
+ # http.start do |h|
28
+ # request = Net::HTTP::Get.new('/', headers)
29
+ # response = http.request(request)
30
+ # content=response.plain_body # Method from our library
31
+ # puts "Transferred: #{response.body.length} bytes"
32
+ # puts "Compression: #{response['content-encoding']}"
33
+ # puts "Extracted: #{response.plain_body.length} bytes"
34
+ # end
35
+ #
36
+
37
+ require 'net/http'
38
+ require 'zlib'
39
+ require 'stringio'
40
+
41
+ class Net::HTTPResponse
42
+ # Return the uncompressed content
43
+ def plain_body
44
+ encoding=self['content-encoding']
45
+ content=nil
46
+ if encoding then
47
+ case encoding
48
+ when 'gzip'
49
+ i=Zlib::GzipReader.new(StringIO.new(self.body))
50
+ content=i.read
51
+ when 'deflate'
52
+ i=Zlib::Inflate.new
53
+ content=i.inflate(self.body)
54
+ else
55
+ raise "Unknown encoding - #{encoding}"
56
+ end
57
+ else
58
+ content=self.body
59
+ end
60
+ return content
61
+ end
62
+ end
@@ -0,0 +1,182 @@
1
+ require File.dirname(__FILE__) + '/test_helper.rb'
2
+ require 'test/unit'
3
+ require 'rubygems'
4
+ require 'mocha'
5
+ RAILS_ENV = 'test'
6
+
7
+ class TestMixin
8
+ class MockRequest
9
+ attr_accessor :format
10
+ end
11
+ class MockResponse
12
+ attr_accessor :body
13
+ end
14
+
15
+ include Rubaidh::GoogleAnalyticsMixin
16
+ attr_accessor :request, :response
17
+
18
+ def initialize
19
+ self.request = MockRequest.new
20
+ self.response = MockResponse.new
21
+ end
22
+
23
+ # override the mixin's method
24
+ def google_analytics_code
25
+ "Google Code"
26
+ end
27
+ end
28
+
29
+
30
+ class GoogleAnalyticsTest < Test::Unit::TestCase
31
+ def setup
32
+ @ga = Rubaidh::GoogleAnalytics.new
33
+ @ga.tracker_id = "the tracker id"
34
+ end
35
+
36
+ def test_createable
37
+ assert_not_nil(@ga)
38
+ end
39
+
40
+ def test_domain_name_defaults_to_nil
41
+ assert_nil(@ga.domain_name)
42
+ end
43
+
44
+ def test_legacy_mode_defaults_to_false
45
+ assert_equal(false, @ga.legacy_mode)
46
+ end
47
+
48
+ def test_default_analytics_url
49
+ assert_equal("http://www.google-analytics.com/urchin.js", @ga.analytics_url)
50
+ end
51
+
52
+ def test_default_analytics_ssl_url
53
+ assert_equal('https://ssl.google-analytics.com/urchin.js', @ga.analytics_ssl_url)
54
+ end
55
+
56
+ def test_default_environments
57
+ assert_equal(false, @ga.environments.include?('test'))
58
+ assert_equal(false, @ga.environments.include?('development'))
59
+ assert_equal(true, @ga.environments.include?('production'))
60
+ end
61
+
62
+ def test_default_formats
63
+ assert_equal(false, @ga.formats.include?(:xml))
64
+ assert_equal(true, @ga.formats.include?(:html))
65
+ end
66
+
67
+ def test_defer_load_defaults_to_true
68
+ assert_equal(true, @ga.defer_load)
69
+ end
70
+
71
+ def test_local_javascript_defaults_to_false
72
+ assert_equal(false, @ga.local_javascript)
73
+ end
74
+
75
+ # test self.enabled
76
+ def test_enabled_requires_tracker_id
77
+ Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns(nil)
78
+ assert_raise(Rubaidh::GoogleAnalyticsConfigurationError) { Rubaidh::GoogleAnalytics.enabled?(:html) }
79
+ end
80
+
81
+ def test_enabled_requires_analytics_url
82
+ Rubaidh::GoogleAnalytics.stubs(:analytics_url).returns(nil)
83
+ assert_raise(Rubaidh::GoogleAnalyticsConfigurationError) { Rubaidh::GoogleAnalytics.enabled?(:html) }
84
+ end
85
+
86
+ def test_enabled_returns_false_if_current_environment_not_enabled
87
+ Rubaidh::GoogleAnalytics.stubs(:environments).returns(['production'])
88
+ assert_equal(false, Rubaidh::GoogleAnalytics.enabled?(:html))
89
+ end
90
+
91
+ def test_enabled_with_default_format
92
+ Rubaidh::GoogleAnalytics.stubs(:environments).returns(['test'])
93
+ assert_equal(true, Rubaidh::GoogleAnalytics.enabled?(:html))
94
+ end
95
+
96
+ def test_enabled_with_not_included_format
97
+ Rubaidh::GoogleAnalytics.stubs(:environments).returns(['test'])
98
+ assert_equal(false, Rubaidh::GoogleAnalytics.enabled?(:xml))
99
+ end
100
+
101
+ def test_enabled_with_added_format
102
+ Rubaidh::GoogleAnalytics.stubs(:environments).returns(['test'])
103
+ Rubaidh::GoogleAnalytics.stubs(:formats).returns([:xml])
104
+ assert_equal(true, Rubaidh::GoogleAnalytics.enabled?(:xml))
105
+ end
106
+
107
+ # test request_tracker_id
108
+ def test_request_tracker_id_without_override
109
+ Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns("1234")
110
+ assert_equal("1234", Rubaidh::GoogleAnalytics.request_tracker_id)
111
+ end
112
+
113
+ def test_request_tracker_id_with_override
114
+ Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns("1234")
115
+ Rubaidh::GoogleAnalytics.override_tracker_id = "4567"
116
+ assert_equal("4567", Rubaidh::GoogleAnalytics.request_tracker_id)
117
+ end
118
+
119
+ def test_request_tracker_id_resets_override
120
+ Rubaidh::GoogleAnalytics.override_tracker_id = "4567"
121
+ Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns("1234")
122
+ foo = Rubaidh::GoogleAnalytics.request_tracker_id
123
+ assert_nil(Rubaidh::GoogleAnalytics.override_tracker_id)
124
+ end
125
+
126
+ # test request_tracked_path
127
+ def test_request_tracked_path_without_override
128
+ assert_equal('', Rubaidh::GoogleAnalytics.request_tracked_path)
129
+ end
130
+
131
+ def test_request_tracked_path_with_override
132
+ Rubaidh::GoogleAnalytics.override_trackpageview = "/my/path"
133
+ assert_equal("'/my/path'", Rubaidh::GoogleAnalytics.request_tracked_path)
134
+ end
135
+
136
+ def test_request_tracked_path_resets_override
137
+ Rubaidh::GoogleAnalytics.override_trackpageview = "/my/path"
138
+ foo = Rubaidh::GoogleAnalytics.request_tracked_path
139
+ assert_nil(Rubaidh::GoogleAnalytics.override_trackpageview)
140
+ end
141
+
142
+ # Test the before_filter method does what we expect by subsituting the body tags and inserting
143
+ # some google code for us automagically.
144
+ def test_add_google_analytics_code
145
+ # setup our test mixin
146
+ mixin = TestMixin.new
147
+
148
+ # bog standard body tag
149
+ Rubaidh::GoogleAnalytics.defer_load = false
150
+ mixin.response.body = "<body><p>some text</p></body>"
151
+ mixin.add_google_analytics_code
152
+ assert_equal mixin.response.body, '<body>Google Code<p>some text</p></body>'
153
+
154
+ Rubaidh::GoogleAnalytics.defer_load = true
155
+ mixin.response.body = "<body><p>some text</p></body>"
156
+ mixin.add_google_analytics_code
157
+ assert_equal mixin.response.body, '<body><p>some text</p>Google Code</body>'
158
+
159
+ # body tag upper cased (ignoring this is semantically incorrect)
160
+ Rubaidh::GoogleAnalytics.defer_load = false
161
+ mixin.response.body = "<BODY><p>some text</p></BODY>"
162
+ mixin.add_google_analytics_code
163
+ assert_equal mixin.response.body, '<BODY>Google Code<p>some text</p></BODY>'
164
+
165
+ Rubaidh::GoogleAnalytics.defer_load = true
166
+ mixin.response.body = "<BODY><p>some text</p></BODY>"
167
+ mixin.add_google_analytics_code
168
+ assert_equal mixin.response.body, '<BODY><p>some text</p>Google Code</body>'
169
+
170
+ # body tag has additional attributes
171
+ Rubaidh::GoogleAnalytics.defer_load = false
172
+ mixin.response.body = '<body style="background-color:red"><p>some text</p></body>'
173
+ mixin.add_google_analytics_code
174
+ assert_equal mixin.response.body, '<body style="background-color:red">Google Code<p>some text</p></body>'
175
+
176
+ Rubaidh::GoogleAnalytics.defer_load = true
177
+ mixin.response.body = '<body style="background-color:red"><p>some text</p></body>'
178
+ mixin.add_google_analytics_code
179
+ assert_equal mixin.response.body, '<body style="background-color:red"><p>some text</p>Google Code</body>'
180
+ end
181
+
182
+ end
@@ -0,0 +1,8 @@
1
+ ENV['RAILS_ENV'] = 'test'
2
+
3
+ require 'rubygems'
4
+ require 'test/unit'
5
+
6
+ require File.expand_path(File.dirname(__FILE__) + '/../lib/rubaidh/google_analytics.rb')
7
+ require File.expand_path(File.dirname(__FILE__) + '/../lib/rubaidh/view_helpers.rb')
8
+
@@ -0,0 +1,56 @@
1
+ require File.dirname(__FILE__) + '/test_helper.rb'
2
+ include Rubaidh::GoogleAnalyticsViewHelper
3
+ include ActionView::Helpers::UrlHelper
4
+ include ActionView::Helpers::TagHelper
5
+
6
+ class ViewHelpersTest < Test::Unit::TestCase
7
+
8
+ def setup
9
+ Rubaidh::GoogleAnalytics.defer_load = false
10
+ end
11
+
12
+ def test_link_to_tracked_should_return_a_tracked_link
13
+ assert_equal "<a href=\"http://www.example.com\" onclick=\"javascript:pageTracker._trackPageview('/sites/linked');\">Link</a>", link_to_tracked('Link', '/sites/linked', "http://www.example.com" )
14
+ end
15
+
16
+ def test_link_to_tracked_with_legacy_should_return_a_tracked_link
17
+ Rubaidh::GoogleAnalytics.legacy_mode = true
18
+ assert_equal "<a href=\"http://www.example.com\" onclick=\"javascript:urchinTracker('/sites/linked');\">Link</a>", link_to_tracked('Link', '/sites/linked', "http://www.example.com" )
19
+ end
20
+
21
+ def test_link_to_tracked_should_error_if_defer_load
22
+ Rubaidh::GoogleAnalytics.defer_load = true
23
+ assert_raise(Rubaidh::AnalyticsError) { link_to_tracked('Link', '/sites/linked', "http://www.example.com" ) }
24
+ end
25
+
26
+ def test_link_to_tracked_if_with_true_should_return_a_tracked_link
27
+ assert_equal "<a href=\"http://www.example.com\" onclick=\"javascript:pageTracker._trackPageview('/sites/linked');\">Link</a>", link_to_tracked_if(true, 'Link', '/sites/linked', "http://www.example.com" )
28
+ end
29
+
30
+ def test_link_to_tracked_if_with_false_should_return_unlinked_text
31
+ assert_equal "Link", link_to_tracked_if(false, 'Link', '/sites/linked', "http://www.example.com" )
32
+ end
33
+
34
+ def test_link_to_tracked_if_should_error_if_defer_load
35
+ Rubaidh::GoogleAnalytics.defer_load = true
36
+ assert_raise(Rubaidh::AnalyticsError) { link_to_tracked_if(false, 'Link', '/sites/linked', "http://www.example.com" ) }
37
+ end
38
+
39
+ def test_link_to_tracked_unless_with_false_should_return_a_tracked_link
40
+ assert_equal "<a href=\"http://www.example.com\" onclick=\"javascript:pageTracker._trackPageview('/sites/linked');\">Link</a>", link_to_tracked_unless(false, 'Link', '/sites/linked', "http://www.example.com" )
41
+ end
42
+
43
+ def test_link_to_tracked_unless_with_true_should_return_unlinked_text
44
+ assert_equal "Link", link_to_tracked_unless(true, 'Link', '/sites/linked', "http://www.example.com" )
45
+ end
46
+
47
+ def test_link_to_tracked_unless_should_error_if_defer_load
48
+ Rubaidh::GoogleAnalytics.defer_load = true
49
+ assert_raise(Rubaidh::AnalyticsError) { link_to_tracked_unless(false, 'Link', '/sites/linked', "http://www.example.com" ) }
50
+ end
51
+
52
+ def test_link_to_tracked_unless_current
53
+ #postponed
54
+ end
55
+
56
+ end
metadata ADDED
@@ -0,0 +1,88 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: kyusik-google_analytics
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.1.5
5
+ platform: ruby
6
+ authors:
7
+ - Graeme Mathieson
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-04-28 00:00:00 -07:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: actionpack
17
+ type: :runtime
18
+ version_requirement:
19
+ version_requirements: !ruby/object:Gem::Requirement
20
+ requirements:
21
+ - - ">="
22
+ - !ruby/object:Gem::Version
23
+ version: "0"
24
+ version:
25
+ - !ruby/object:Gem::Dependency
26
+ name: activesupport
27
+ type: :runtime
28
+ version_requirement:
29
+ version_requirements: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: "0"
34
+ version:
35
+ description: |
36
+ By default this gem will output google analytics code forevery page automatically, if it's configured correctly.This is done by adding:
37
+ Rubaidh::GoogleAnalytics.tracker_id = 'UA-12345-67'
38
+
39
+ email: mathie@rubaidh.com
40
+ executables: []
41
+
42
+ extensions: []
43
+
44
+ extra_rdoc_files: []
45
+
46
+ files:
47
+ - CREDITS
48
+ - MIT-LICENSE
49
+ - README.rdoc
50
+ - Rakefile
51
+ - rails/init.rb
52
+ - test/google_analytics_test.rb
53
+ - test/test_helper.rb
54
+ - test/view_helpers_test.rb
55
+ - lib/rubaidh.rb
56
+ - lib/rubaidh/google_analytics.rb
57
+ - lib/rubaidh/view_helpers.rb
58
+ - tasks/google_analytics.rake
59
+ has_rdoc: true
60
+ homepage: http://rubaidh.com/portfolio/open-source/google-analytics/
61
+ licenses: []
62
+
63
+ post_install_message:
64
+ rdoc_options: []
65
+
66
+ require_paths:
67
+ - lib
68
+ required_ruby_version: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: "0"
73
+ version:
74
+ required_rubygems_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: "0"
79
+ version:
80
+ requirements: []
81
+
82
+ rubyforge_project: rubaidh
83
+ rubygems_version: 1.3.5
84
+ signing_key:
85
+ specification_version: 3
86
+ summary: "[Rails] Easily enable Google Analytics support in your Rails application."
87
+ test_files: []
88
+