google_analytics 1.1.1

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. :-)
data/MIT-LICENSE ADDED
@@ -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.
data/README.rdoc ADDED
@@ -0,0 +1,124 @@
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
+ == Note
30
+
31
+ This version of the plugin uses the new Google Analytics code (ga.js) by
32
+ default. To use the legacy tracking code add the following line to your
33
+ <tt>config/environment.rb</tt>:
34
+
35
+ Rubaidh::GoogleAnalytics.legacy_mode = true
36
+
37
+ == Tracking outbound Links
38
+
39
+ Google Analytics only tracks intra-site links by default. To create an
40
+ outbound link that is tracked use the link_to_tracked helper:
41
+
42
+ link_to_tracked(name, track_path = "/", options = {}, html_options = {})
43
+
44
+ You can use the track_path parameter to group your outbound links into logical
45
+ folders inside of Google Analytics.
46
+
47
+ The other forms of link_to are also supported:
48
+
49
+ link_to_tracked_if(condition, name, track_path = "/", options = {}, html_options = {}, &block)
50
+ link_to_tracked_unless(condition, name, track_path = "/", options = {}, html_options = {}, &block)
51
+ link_to_tracked_unless_current(name, track_path = "/", options = {}, html_options = {}, &block)
52
+
53
+ To track outbound links, you should set
54
+
55
+ Rubaidh::GoogleAnalytics.defer_load = false
56
+
57
+ This will move the tracking javascript to the top of your page.
58
+ (see http://www.google.com/support/googleanalytics/bin/answer.py?answer=55527&topic=11006)
59
+
60
+ Tracked links respect the legacy_mode flag.
61
+
62
+ Note: Link-tracking works by inserting onclick() code in the HTML. Because of
63
+ this, it will overwrite any onclick that you insert in the html_options hash.
64
+
65
+ == Using local copies of the Analytics Javascript files
66
+
67
+ Under certain circumstances you might find it valuable to serve a copy of the
68
+ Analytics JavaScript directly from your server to your visitors, and not
69
+ directly from Google. If your visitors are geograhically very far from Google,
70
+ or if they have low quality international bandwidth, the loading time for the
71
+ Analytics JS might kill the user experience and force you to remove the
72
+ valuable tracking code from your site.
73
+
74
+ This plugin now supports local copies of the legacy and new Analytics
75
+ JavaScript files, updated via a rake task and served courtesy of the Rails
76
+ AssetTagHelper methods. So even if you use asset hosts, the JS will be served
77
+ from the correct source and under the correct protocol (HTTP/HTTPS).
78
+
79
+ To enable cached copies and the following to your initialization code:
80
+
81
+ Rubaidh::GoogleAnalytics.local_javascript = true
82
+
83
+ Use the following rake task to update the local copy of the JavaScript file:
84
+
85
+ rake google_analytics:updates
86
+
87
+ To keep the file updated you can add the following to your Capistrano
88
+ configuration:
89
+
90
+ after "deploy:symlink", "deploy:google_analytics"
91
+
92
+ namespace :deploy do
93
+ desc "Update local Google Analytics files"
94
+ task :google_analytics, :role => :web do
95
+ run "cd #{current_path} && rake google_analytics:update RAILS_ENV=#{ENV['RAILS_ENV']}"
96
+ end
97
+ end
98
+
99
+ The above Capistrano recipe will almost certainly need some adjustments based
100
+ on how you run your deployments, but you should get the idea.
101
+
102
+ == Overriding application-default values
103
+
104
+ If you're using one Rails application to serve pages across multiple domains,
105
+ you may wish to override the domain and tracker ID values on a
106
+ controller-by-controller or view-by-view basis. You can do this by setting the
107
+ override_domain_name and override_tracker_id properties. These properties are
108
+ automatically reset after each use, so the values you set for domain_name and
109
+ tracker_id (usually in an initializer) will apply to all other requests.
110
+
111
+ before_filter :local_analytics
112
+
113
+ def local_analytics
114
+ Rubaidh::GoogleAnalytics.override_domain_name = 'foo.com'
115
+ Rubaidh::GoogleAnalytics.override_tracker_id = 'UA-123456-7'
116
+ end
117
+
118
+ See the documentation for the GoogleAnalytics class for other configuration
119
+ options.
120
+
121
+ Note: You will need to have the mocha gem installed to run the tests for this
122
+ plugin.
123
+
124
+ Copyright (c) 2006-2008 Rubaidh Ltd, released under the MIT license.
data/Rakefile ADDED
@@ -0,0 +1,40 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+ require 'rake/gempackagetask'
5
+ require 'rubyforge'
6
+
7
+ desc 'Default: run unit tests.'
8
+ task :default => :test
9
+
10
+ task :clean => [:clobber_rdoc, :clobber_package]
11
+
12
+ desc 'Test the google_analytics plugin.'
13
+ Rake::TestTask.new(:test) do |t|
14
+ t.libs << 'lib'
15
+ t.pattern = 'test/**/*_test.rb'
16
+ t.verbose = true
17
+ end
18
+
19
+ desc 'Generate documentation for the google_analytics plugin.'
20
+ Rake::RDocTask.new(:rdoc) do |rdoc|
21
+ rdoc.rdoc_dir = 'rdoc'
22
+ rdoc.title = 'GoogleAnalytics'
23
+ rdoc.options << '--line-numbers' << '--inline-source'
24
+ rdoc.rdoc_files.include('README.rdoc')
25
+ rdoc.rdoc_files.include('lib/**/*.rb')
26
+ end
27
+
28
+ gem_spec = eval(File.read('google_analytics.gemspec'))
29
+
30
+ Rake::GemPackageTask.new(gem_spec) do |p|
31
+ p.need_tar = false
32
+ p.need_zip = false
33
+ end
34
+
35
+ desc 'Package and upload the release to rubyforge.'
36
+ task :release => [:clean, :package] do |t|
37
+ rubyforge = RubyForge.new.configure
38
+ rubyforge.login
39
+ rubyforge.add_release "rubaidh", "google_analytics", gem_spec.version, "pkg/google_analytics-#{gem_spec.version}.gem"
40
+ end
@@ -0,0 +1,237 @@
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.defer_load
21
+ response.body.sub! '</body>', "#{google_analytics_code}</body>" if response.body.respond_to?(:sub!)
22
+ else
23
+ response.body.sub! '<body>', "<body>#{google_analytics_code}" if response.body.respond_to?(:sub!)
24
+ end
25
+ end
26
+ end
27
+
28
+ class GoogleAnalyticsConfigurationError < StandardError; end
29
+
30
+ # The core functionality to connect a Rails application
31
+ # to a Google Analytics installation.
32
+ class GoogleAnalytics
33
+
34
+ @@tracker_id = nil
35
+ ##
36
+ # :singleton-method:
37
+ # Specify the Google Analytics ID for this web site. This can be found
38
+ # as the value of +_getTracker+ if you are using the new (ga.js) tracking
39
+ # code, or the value of +_uacct+ if you are using the old (urchin.js)
40
+ # tracking code.
41
+ cattr_accessor :tracker_id
42
+
43
+ @@domain_name = nil
44
+ ##
45
+ # :singleton-method:
46
+ # Specify a different domain name from the default. You'll want to use
47
+ # this if you have several subdomains that you want to combine into
48
+ # one report. See the Google Analytics documentation for more
49
+ # information.
50
+ cattr_accessor :domain_name
51
+
52
+ @@legacy_mode = false
53
+ ##
54
+ # :singleton-method:
55
+ # Specify whether the legacy Google Analytics code should be used. By
56
+ # default, the new Google Analytics code is used.
57
+ cattr_accessor :legacy_mode
58
+
59
+ @@analytics_url = 'http://www.google-analytics.com/urchin.js'
60
+ ##
61
+ # :singleton-method:
62
+ # The URL that analytics information is sent to. This defaults to the
63
+ # standard Google Analytics URL, and you're unlikely to need to change it.
64
+ # This has no effect unless you're in legacy mode.
65
+ cattr_accessor :analytics_url
66
+
67
+ @@analytics_ssl_url = 'https://ssl.google-analytics.com/urchin.js'
68
+ ##
69
+ # :singleton-method:
70
+ # The URL that analytics information is sent to when using SSL. This defaults to the
71
+ # standard Google Analytics URL, and you're unlikely to need to change it.
72
+ # This has no effect unless you're in legacy mode.
73
+ cattr_accessor :analytics_ssl_url
74
+
75
+ @@environments = ['production']
76
+ ##
77
+ # :singleton-method:
78
+ # The environments in which to enable the Google Analytics code. Defaults
79
+ # to 'production' only. Supply an array of environment names to change this.
80
+ cattr_accessor :environments
81
+
82
+ @@formats = [:html, :all]
83
+ ##
84
+ # :singleton-method:
85
+ # The request formats where tracking code should be added. Defaults to +[:html, :all]+. The entry for
86
+ # +:all+ is necessary to make Google recognize that tracking is installed on a
87
+ # site; it is not the same as responding to all requests. Supply an array
88
+ # of formats to change this.
89
+ cattr_accessor :formats
90
+
91
+ @@defer_load = true
92
+ ##
93
+ # :singleton-method:
94
+ # Set this to true (the default) if you want to load the Analytics javascript at
95
+ # the bottom of page. Set this to false if you want to load the Analytics
96
+ # javascript at the top of the page. The page will render faster if you set this to
97
+ # true, but that will break the linking functions in Rubaidh::GoogleAnalyticsViewHelper.
98
+ cattr_accessor :defer_load
99
+
100
+ @@local_javascript = false
101
+ ##
102
+ # :singleton-method:
103
+ # Set this to true to use a local copy of the ga.js (or urchin.js) file.
104
+ # This gives you the added benefit of serving the JS directly from your
105
+ # server, which in case of a big geographical difference between your server
106
+ # and Google's can speed things up for your visitors. Use the
107
+ # 'google_analytics:update' rake task to update the local JS copies.
108
+ cattr_accessor :local_javascript
109
+
110
+ ##
111
+ # :singleton-method:
112
+ # Set this to override the initialized domain name for a single render. Useful
113
+ # when you're serving to multiple hosts from a single codebase. Typically you'd
114
+ # set up a before filter in the appropriate controller:
115
+ # before_filter :override_domain_name
116
+ # def override_domain_name
117
+ # Rubaidh::GoogleAnalytics.override_domain_name = 'foo.com'
118
+ # end
119
+ cattr_accessor :override_domain_name
120
+
121
+ ##
122
+ # :singleton-method:
123
+ # Set this to override the initialized tracker ID for a single render. Useful
124
+ # when you're serving to multiple hosts from a single codebase. Typically you'd
125
+ # set up a before filter in the appropriate controller:
126
+ # before_filter :override_tracker_id
127
+ # def override_tracker_id
128
+ # Rubaidh::GoogleAnalytics.override_tracker_id = 'UA-123456-7'
129
+ # end
130
+ cattr_accessor :override_tracker_id
131
+
132
+ ##
133
+ # :singleton-method:
134
+ # Set this to override the automatically generated path to the page in the
135
+ # Google Analytics reports for a single render. Typically you'd set this up on an
136
+ # action-by-action basis:
137
+ # def show
138
+ # Rubaidh::GoogleAnalytics.override_trackpageview = "path_to_report"
139
+ # ...
140
+ cattr_accessor :override_trackpageview
141
+
142
+ # Return true if the Google Analytics system is enabled and configured
143
+ # correctly for the specified format
144
+ def self.enabled?(format)
145
+ raise Rubaidh::GoogleAnalyticsConfigurationError if tracker_id.blank? || analytics_url.blank?
146
+ environments.include?(RAILS_ENV) && formats.include?(format.to_sym)
147
+ end
148
+
149
+ # Construct the javascript code to be inserted on the calling page. The +ssl+
150
+ # parameter can be used to force the SSL version of the code in legacy mode only.
151
+ def self.google_analytics_code(ssl = false)
152
+ return legacy_google_analytics_code(ssl) if legacy_mode
153
+
154
+ extra_code = domain_name.blank? ? nil : "pageTracker._setDomainName(\"#{domain_name}\");"
155
+ if !override_domain_name.blank?
156
+ extra_code = "pageTracker._setDomainName(\"#{override_domain_name}\");"
157
+ self.override_domain_name = nil
158
+ end
159
+
160
+ code = if local_javascript
161
+ <<-HTML
162
+ <script src="#{LocalAssetTagHelper.new.javascript_path( 'ga.js' )}" type="text/javascript">
163
+ </script>
164
+ HTML
165
+ else
166
+ <<-HTML
167
+ <script type="text/javascript">
168
+ var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
169
+ document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
170
+ </script>
171
+ HTML
172
+ end
173
+
174
+ code << <<-HTML
175
+ <script type="text/javascript">
176
+ <!--//--><![CDATA[//><!--
177
+ var pageTracker = _gat._getTracker('#{request_tracker_id}');
178
+ #{extra_code}
179
+ pageTracker._initData();
180
+ pageTracker._trackPageview(#{request_tracked_path});
181
+ //--><!]]>
182
+ </script>
183
+ HTML
184
+ end
185
+
186
+ # Construct the legacy version of the Google Analytics code. The +ssl+
187
+ # parameter specifies whether or not to return the SSL version of the code.
188
+ def self.legacy_google_analytics_code(ssl = false)
189
+ extra_code = domain_name.blank? ? nil : "_udn = \"#{domain_name}\";"
190
+ if !override_domain_name.blank?
191
+ extra_code = "_udn = \"#{override_domain_name}\";"
192
+ self.override_domain_name = nil
193
+ end
194
+
195
+ url = legacy_analytics_js_url(ssl)
196
+
197
+ code = <<-HTML
198
+ <script src="#{url}" type="text/javascript">
199
+ </script>
200
+ <script type="text/javascript">
201
+ _uacct = "#{request_tracker_id}";
202
+ #{extra_code}
203
+ urchinTracker(#{request_tracked_path});
204
+ </script>
205
+ HTML
206
+ end
207
+
208
+ # Generate the correct URL for the legacy Analytics JS file
209
+ def self.legacy_analytics_js_url(ssl = false)
210
+ if local_javascript
211
+ LocalAssetTagHelper.new.javascript_path( 'urchin.js' )
212
+ else
213
+ ssl ? analytics_ssl_url : analytics_url
214
+ end
215
+ end
216
+
217
+ # Determine the tracker ID for this request
218
+ def self.request_tracker_id
219
+ use_tracker_id = override_tracker_id.blank? ? tracker_id : override_tracker_id
220
+ self.override_tracker_id = nil
221
+ use_tracker_id
222
+ end
223
+
224
+ # Determine the path to report for this request
225
+ def self.request_tracked_path
226
+ use_tracked_path = override_trackpageview.blank? ? '' : "'#{override_trackpageview}'"
227
+ self.override_trackpageview = nil
228
+ use_tracked_path
229
+ end
230
+
231
+ end
232
+
233
+ class LocalAssetTagHelper # :nodoc:
234
+ # For helping with local javascripts
235
+ include ActionView::Helpers::AssetTagHelper
236
+ end
237
+ 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
+
data/lib/rubaidh.rb ADDED
@@ -0,0 +1,2 @@
1
+ module Rubaidh #:nodoc:
2
+ end
data/rails/init.rb ADDED
@@ -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,119 @@
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 GoogleAnalyticsTest < Test::Unit::TestCase
8
+ def setup
9
+ @ga = Rubaidh::GoogleAnalytics.new
10
+ @ga.tracker_id = "the tracker id"
11
+ end
12
+
13
+ def test_createable
14
+ assert_not_nil(@ga)
15
+ end
16
+
17
+ def test_domain_name_defaults_to_nil
18
+ assert_nil(@ga.domain_name)
19
+ end
20
+
21
+ def test_legacy_mode_defaults_to_false
22
+ assert_equal(false, @ga.legacy_mode)
23
+ end
24
+
25
+ def test_default_analytics_url
26
+ assert_equal("http://www.google-analytics.com/urchin.js", @ga.analytics_url)
27
+ end
28
+
29
+ def test_default_analytics_ssl_url
30
+ assert_equal('https://ssl.google-analytics.com/urchin.js', @ga.analytics_ssl_url)
31
+ end
32
+
33
+ def test_default_environments
34
+ assert_equal(false, @ga.environments.include?('test'))
35
+ assert_equal(false, @ga.environments.include?('development'))
36
+ assert_equal(true, @ga.environments.include?('production'))
37
+ end
38
+
39
+ def test_default_formats
40
+ assert_equal(false, @ga.formats.include?(:xml))
41
+ assert_equal(true, @ga.formats.include?(:html))
42
+ end
43
+
44
+ def test_defer_load_defaults_to_true
45
+ assert_equal(true, @ga.defer_load)
46
+ end
47
+
48
+ def test_local_javascript_defaults_to_false
49
+ assert_equal(false, @ga.local_javascript)
50
+ end
51
+
52
+ # test self.enabled
53
+ def test_enabled_requires_tracker_id
54
+ Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns(nil)
55
+ assert_raise(Rubaidh::GoogleAnalyticsConfigurationError) { Rubaidh::GoogleAnalytics.enabled?(:html) }
56
+ end
57
+
58
+ def test_enabled_requires_analytics_url
59
+ Rubaidh::GoogleAnalytics.stubs(:analytics_url).returns(nil)
60
+ assert_raise(Rubaidh::GoogleAnalyticsConfigurationError) { Rubaidh::GoogleAnalytics.enabled?(:html) }
61
+ end
62
+
63
+ def test_enabled_returns_false_if_current_environment_not_enabled
64
+ Rubaidh::GoogleAnalytics.stubs(:environments).returns(['production'])
65
+ assert_equal(false, Rubaidh::GoogleAnalytics.enabled?(:html))
66
+ end
67
+
68
+ def test_enabled_with_default_format
69
+ Rubaidh::GoogleAnalytics.stubs(:environments).returns(['test'])
70
+ assert_equal(true, Rubaidh::GoogleAnalytics.enabled?(:html))
71
+ end
72
+
73
+ def test_enabled_with_not_included_format
74
+ Rubaidh::GoogleAnalytics.stubs(:environments).returns(['test'])
75
+ assert_equal(false, Rubaidh::GoogleAnalytics.enabled?(:xml))
76
+ end
77
+
78
+ def test_enabled_with_added_format
79
+ Rubaidh::GoogleAnalytics.stubs(:environments).returns(['test'])
80
+ Rubaidh::GoogleAnalytics.stubs(:formats).returns([:xml])
81
+ assert_equal(true, Rubaidh::GoogleAnalytics.enabled?(:xml))
82
+ end
83
+
84
+ # test request_tracker_id
85
+ def test_request_tracker_id_without_override
86
+ Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns("1234")
87
+ assert_equal("1234", Rubaidh::GoogleAnalytics.request_tracker_id)
88
+ end
89
+
90
+ def test_request_tracker_id_with_override
91
+ Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns("1234")
92
+ Rubaidh::GoogleAnalytics.override_tracker_id = "4567"
93
+ assert_equal("4567", Rubaidh::GoogleAnalytics.request_tracker_id)
94
+ end
95
+
96
+ def test_request_tracker_id_resets_override
97
+ Rubaidh::GoogleAnalytics.override_tracker_id = "4567"
98
+ Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns("1234")
99
+ foo = Rubaidh::GoogleAnalytics.request_tracker_id
100
+ assert_nil(Rubaidh::GoogleAnalytics.override_tracker_id)
101
+ end
102
+
103
+ # test request_tracked_path
104
+ def test_request_tracked_path_without_override
105
+ assert_equal('', Rubaidh::GoogleAnalytics.request_tracked_path)
106
+ end
107
+
108
+ def test_request_tracked_path_with_override
109
+ Rubaidh::GoogleAnalytics.override_trackpageview = "/my/path"
110
+ assert_equal("'/my/path'", Rubaidh::GoogleAnalytics.request_tracked_path)
111
+ end
112
+
113
+ def test_request_tracked_path_resets_override
114
+ Rubaidh::GoogleAnalytics.override_trackpageview = "/my/path"
115
+ foo = Rubaidh::GoogleAnalytics.request_tracked_path
116
+ assert_nil(Rubaidh::GoogleAnalytics.override_trackpageview)
117
+ end
118
+
119
+ 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,83 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: google_analytics
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Graeme Mathieson
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-01-02 00:00:00 +00: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: "By default this gem will output google analytics code forevery page automatically, if it's configured correctly.This is done by adding: Rubaidh::GoogleAnalytics.tracker_id = 'UA-12345-67'"
36
+ email: mathie@rubaidh.com
37
+ executables: []
38
+
39
+ extensions: []
40
+
41
+ extra_rdoc_files: []
42
+
43
+ files:
44
+ - CREDITS
45
+ - MIT-LICENSE
46
+ - README.rdoc
47
+ - Rakefile
48
+ - rails/init.rb
49
+ - test/google_analytics_test.rb
50
+ - test/test_helper.rb
51
+ - test/view_helpers_test.rb
52
+ - lib/rubaidh.rb
53
+ - lib/rubaidh/google_analytics.rb
54
+ - lib/rubaidh/view_helpers.rb
55
+ - tasks/google_analytics.rake
56
+ has_rdoc: true
57
+ homepage: http://rubaidh.com/portfolio/open-source/google-analytics/
58
+ post_install_message:
59
+ rdoc_options: []
60
+
61
+ require_paths:
62
+ - lib
63
+ required_ruby_version: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: "0"
68
+ version:
69
+ required_rubygems_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: "0"
74
+ version:
75
+ requirements: []
76
+
77
+ rubyforge_project: rubaidh
78
+ rubygems_version: 1.3.1
79
+ signing_key:
80
+ specification_version: 2
81
+ summary: "[Rails] Easily enable Google Analytics support in your Rails application."
82
+ test_files: []
83
+