shingara-garb 0.7.6

Sign up to get free protection for your applications and to get access to all the features.
Files changed (41) hide show
  1. data/README.md +255 -0
  2. data/Rakefile +56 -0
  3. data/lib/garb.rb +42 -0
  4. data/lib/garb/account.rb +29 -0
  5. data/lib/garb/authentication_request.rb +53 -0
  6. data/lib/garb/data_request.rb +42 -0
  7. data/lib/garb/filter_parameters.rb +41 -0
  8. data/lib/garb/profile.rb +37 -0
  9. data/lib/garb/profile_reports.rb +15 -0
  10. data/lib/garb/report.rb +26 -0
  11. data/lib/garb/report_parameter.rb +25 -0
  12. data/lib/garb/report_response.rb +33 -0
  13. data/lib/garb/reports.rb +5 -0
  14. data/lib/garb/reports/bounces.rb +5 -0
  15. data/lib/garb/reports/exits.rb +5 -0
  16. data/lib/garb/reports/pageviews.rb +5 -0
  17. data/lib/garb/reports/unique_pageviews.rb +5 -0
  18. data/lib/garb/reports/visits.rb +5 -0
  19. data/lib/garb/resource.rb +92 -0
  20. data/lib/garb/session.rb +35 -0
  21. data/lib/garb/version.rb +13 -0
  22. data/lib/support.rb +39 -0
  23. data/test/fixtures/cacert.pem +67 -0
  24. data/test/fixtures/profile_feed.xml +38 -0
  25. data/test/fixtures/report_feed.xml +46 -0
  26. data/test/test_helper.rb +18 -0
  27. data/test/unit/garb/account_test.rb +53 -0
  28. data/test/unit/garb/authentication_request_test.rb +121 -0
  29. data/test/unit/garb/data_request_test.rb +119 -0
  30. data/test/unit/garb/filter_parameters_test.rb +59 -0
  31. data/test/unit/garb/oauth_session_test.rb +11 -0
  32. data/test/unit/garb/profile_reports_test.rb +29 -0
  33. data/test/unit/garb/profile_test.rb +75 -0
  34. data/test/unit/garb/report_parameter_test.rb +43 -0
  35. data/test/unit/garb/report_response_test.rb +14 -0
  36. data/test/unit/garb/report_test.rb +91 -0
  37. data/test/unit/garb/resource_test.rb +38 -0
  38. data/test/unit/garb/session_test.rb +91 -0
  39. data/test/unit/garb_test.rb +14 -0
  40. data/test/unit/symbol_operator_test.rb +37 -0
  41. metadata +146 -0
@@ -0,0 +1,255 @@
1
+ Garb
2
+ ====
3
+
4
+ http://github.com/vigetlabs/garb
5
+
6
+ Important Changes
7
+ =================
8
+
9
+ Please read CHANGELOG
10
+
11
+ Description
12
+ -----------
13
+
14
+ Provides a Ruby API to the Google Analytics API.
15
+
16
+ http://code.google.com/apis/analytics/docs/gdata/gdataDeveloperGuide.html
17
+
18
+ Basic Usage
19
+ ===========
20
+
21
+ Single User Login
22
+ -----------------
23
+
24
+ > Garb::Session.login(username, password)
25
+
26
+ OAuth Access Token
27
+ ------------------
28
+
29
+ > Garb::Session.access_token = access_token # assign from oauth gem
30
+
31
+ AuthSub Token
32
+ -------------
33
+
34
+ > Garb::Session.auth_sub(token) # assign by AuthSub system
35
+
36
+ Accounts
37
+ --------
38
+
39
+ > Garb::Account.all
40
+
41
+ Profiles
42
+ --------
43
+
44
+ > Garb::Account.first.profiles
45
+
46
+ > Garb::Profile.first('UA-XXXX-XX')
47
+
48
+ > Garb::Profile.all
49
+ > profile = Garb::Profile.all.first
50
+
51
+ Define a Report Class
52
+ ---------------------
53
+
54
+ class Exits
55
+ extend Garb::Resource
56
+
57
+ metrics :exits, :pageviews, :exit_rate
58
+ dimensions :page_path
59
+ sort :exits
60
+
61
+ filters do
62
+ eql(:page_path, 'season')
63
+ end
64
+
65
+ # alternative:
66
+ # filters :page_path.eql => 10
67
+ end
68
+
69
+ Get the Results
70
+ ---------------
71
+
72
+ > Exits.results(profile)
73
+
74
+ OR shorthand
75
+
76
+ > profile.exits
77
+
78
+ Other Parameters
79
+ ----------------
80
+
81
+ * start_date: The date of the period you would like this report to start
82
+ * end_date: The date to end, inclusive
83
+ * limit: The maximum number of results to be returned
84
+ * offset: The starting index
85
+
86
+ Metrics & Dimensions
87
+ --------------------
88
+
89
+ Metrics and Dimensions are very complex because of the ways in which the can and cannot be combined.
90
+
91
+ I suggest reading the google documentation to familiarize yourself with this.
92
+
93
+ http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html#bounceRate
94
+
95
+ When you've returned, you can pass the appropriate combinations (up to 50 metrics and 2 dimenstions)
96
+ to garb, as an array, of symbols. Or you can simply push a symbol into the array.
97
+
98
+ Sorting
99
+ -------
100
+
101
+ Sorting can be done on any metric or dimension defined in the request, with .desc reversing the sort.
102
+
103
+ Building a Report
104
+ -----------------
105
+
106
+ Given the class, session, and profile from above we can do:
107
+
108
+ Exits.results(profile, :limit => 10, :offset => 19)
109
+
110
+ Or, with sorting and filters:
111
+
112
+ Exits.results(profile, :limit => 10, :offset => 19) do
113
+ sort :exits
114
+
115
+ filters do
116
+ contains(:page_path, 'season')
117
+ gt(:exits, 100)
118
+ end
119
+
120
+ # or with a hash
121
+ # filters :page_path.contains => 'season', :exits.gt => 100
122
+ end
123
+
124
+ reports will be an array of OpenStructs with methods for the metrics and dimensions returned.
125
+
126
+ Build a One-Off Report
127
+ ----------------------
128
+
129
+ report = Garb::Report.new(profile)
130
+ report.metrics :pageviews, :exits
131
+ report.dimensions :page_path
132
+ report.sort :exits
133
+
134
+ report.filters do
135
+ contains(:page_path, 'season')
136
+ gte(:exits, 10)
137
+ and
138
+
139
+ # or with a hash
140
+ # report.filters :page_path.contains => 'season', :exits.gt => 100
141
+
142
+ report.results
143
+
144
+ Filtering
145
+ ---------
146
+
147
+ Google Analytics supports a significant number of filtering options.
148
+
149
+ http://code.google.com/apis/analytics/docs/gdata/gdataReference.html#filtering
150
+
151
+ We handle filtering as an array of hashes that you can push into,
152
+ which will be joined together (AND'd)
153
+
154
+ Here is what we can do currently:
155
+ (the operator is a method on a symbol metric or dimension)
156
+
157
+ Operators on metrics:
158
+
159
+ eql => '==',
160
+ not_eql => '!=',
161
+ gt => '>',
162
+ gte => '>=',
163
+ lt => '<',
164
+ lte => '<='
165
+
166
+ Operators on dimensions:
167
+
168
+ matches => '==',
169
+ does_not_match => '!=',
170
+ contains => '=~',
171
+ does_not_contain => '!~',
172
+ substring => '=@',
173
+ not_substring => '!@'
174
+
175
+ Given the previous example one-off report, we can add a line for filter:
176
+
177
+ report.filters do
178
+ eql(:page_path, '/extend/effectively-using-git-with-subversion/')
179
+ end
180
+
181
+ Or, if you're comfortable using symbol operators:
182
+
183
+ report.filters :page_path.eql => '/extend/effectively-using-git-with-subversion/'
184
+
185
+ SSL
186
+ ---
187
+
188
+ Version 0.2.3 includes support for real ssl encryption for SINGLE USER authentication. First do:
189
+
190
+ Garb::Session.login(username, password, :secure => true)
191
+
192
+ Next, be sure to download http://curl.haxx.se/ca/cacert.pem into your application somewhere.
193
+ Then, define a constant CA_CERT_FILE and point to that file.
194
+
195
+ For whatever reason, simply creating a new certificate store and setting the defaults would
196
+ not validate the google ssl certificate as authentic.
197
+
198
+ TODOS
199
+ -----
200
+
201
+ * Read opensearch header in results
202
+ * Investigate new features from GA to see if they're in the API, implement if so
203
+ * clarify AND/OR filtering behavior in code and documentation
204
+
205
+ Requirements
206
+ ------------
207
+
208
+ * crack >= 0.1.6
209
+ * active_support >= 2.2.0
210
+
211
+ Requirements for Testing
212
+ ------------------------
213
+
214
+ * jferris-mocha
215
+ * tpitale-shoulda (works with minitest)
216
+
217
+ Install
218
+ -------
219
+
220
+ sudo gem install garb
221
+
222
+ Contributors
223
+ ------------
224
+
225
+ Many Thanks, for all their help, goes to:
226
+
227
+ * Patrick Reagan
228
+ * Justin Marney
229
+ * Nick Plante
230
+
231
+ License
232
+ -------
233
+
234
+ (The MIT License)
235
+
236
+ Copyright (c) 2010 Viget Labs
237
+
238
+ Permission is hereby granted, free of charge, to any person obtaining
239
+ a copy of this software and associated documentation files (the
240
+ 'Software'), to deal in the Software without restriction, including
241
+ without limitation the rights to use, copy, modify, merge, publish,
242
+ distribute, sublicense, and/or sell copies of the Software, and to
243
+ permit persons to whom the Software is furnished to do so, subject to
244
+ the following conditions:
245
+
246
+ The above copyright notice and this permission notice shall be
247
+ included in all copies or substantial portions of the Software.
248
+
249
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
250
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
251
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
252
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
253
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
254
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
255
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,56 @@
1
+ require 'rubygems'
2
+ require 'rake/gempackagetask'
3
+ require 'rake/testtask'
4
+
5
+ require 'lib/garb/version'
6
+
7
+ task :default => :test
8
+
9
+ spec = Gem::Specification.new do |s|
10
+ s.name = 'garb'
11
+ s.version = Garb::Version.to_s
12
+ s.has_rdoc = false
13
+ s.rubyforge_project = 'viget'
14
+ s.summary = "Google Analytics API Ruby Wrapper"
15
+ s.authors = ['Tony Pitale']
16
+ s.email = 'tony.pitale@viget.com'
17
+ s.homepage = 'http://github.com/vigetlabs/garb'
18
+ s.files = %w(README.md Rakefile) + Dir.glob("lib/**/*")
19
+ s.test_files = Dir.glob("test/**/*")
20
+
21
+ s.add_dependency("crack", [">= 0.1.6"])
22
+ s.add_dependency("activesupport", [">= 2.2.0"])
23
+ end
24
+
25
+ Rake::GemPackageTask.new(spec) do |pkg|
26
+ pkg.gem_spec = spec
27
+ end
28
+
29
+ Rake::TestTask.new do |t|
30
+ t.libs << 'test'
31
+ t.test_files = FileList["test/**/*_test.rb"]
32
+ t.verbose = true
33
+ end
34
+
35
+ desc 'Generate the gemspec to serve this Gem from Github'
36
+ task :github do
37
+ file = File.dirname(__FILE__) + "/#{spec.name}.gemspec"
38
+ File.open(file, 'w') {|f| f << spec.to_ruby }
39
+ puts "Created gemspec: #{file}"
40
+ end
41
+
42
+ begin
43
+ require 'rcov/rcovtask'
44
+
45
+ desc "Generate RCov coverage report"
46
+ Rcov::RcovTask.new(:rcov) do |t|
47
+ t.test_files = FileList['test/**/*_test.rb']
48
+ t.rcov_opts << "-x lib/garb.rb -x lib/garb/version.rb"
49
+ end
50
+ rescue LoadError
51
+ nil
52
+ end
53
+
54
+ task :default => 'test'
55
+
56
+ # EOF
@@ -0,0 +1,42 @@
1
+ $:.unshift File.expand_path(File.dirname(__FILE__))
2
+
3
+ require 'net/http'
4
+ require 'net/https'
5
+
6
+ require 'cgi'
7
+ require 'ostruct'
8
+ require 'crack'
9
+ require 'active_support'
10
+
11
+ require 'garb/version'
12
+ require 'garb/authentication_request'
13
+ require 'garb/data_request'
14
+ require 'garb/session'
15
+ require 'garb/profile_reports'
16
+ require 'garb/profile'
17
+ require 'garb/account'
18
+ require 'garb/filter_parameters'
19
+ require 'garb/report_parameter'
20
+ require 'garb/report_response'
21
+ require 'garb/resource'
22
+ require 'garb/report'
23
+
24
+ require 'support'
25
+
26
+ module Garb
27
+ GA = "http://schemas.google.com/analytics/2008"
28
+
29
+ extend self
30
+
31
+ def to_google_analytics(thing)
32
+ return thing.to_google_analytics if thing.respond_to?(:to_google_analytics)
33
+
34
+ "ga:#{thing.to_s.camelize(:lower)}"
35
+ end
36
+ alias :to_ga :to_google_analytics
37
+
38
+ def from_google_analytics(thing)
39
+ thing.to_s.gsub(/^ga\:/, '').underscore
40
+ end
41
+ alias :from_ga :from_google_analytics
42
+ end
@@ -0,0 +1,29 @@
1
+ module Garb
2
+ class Account
3
+ attr_reader :id, :name, :profiles
4
+
5
+ def initialize(profiles)
6
+ @id = profiles.first.account_id
7
+ @name = profiles.first.account_name
8
+ @profiles = profiles
9
+ end
10
+
11
+ def self.all(session = Session)
12
+ # Profile.all.group_to_array{|p| p.account_id}.map{|profiles| new(profiles)}
13
+
14
+ profile_groups = Profile.all(session).inject({}) do |hash, profile|
15
+ key = profile.account_id
16
+
17
+ if hash.has_key?(key)
18
+ hash[key] << profile
19
+ else
20
+ hash[key] = [profile]
21
+ end
22
+
23
+ hash
24
+ end
25
+
26
+ profile_groups.map {|k,v| v}.map {|profiles| new(profiles)}
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,53 @@
1
+ module Garb
2
+ class AuthenticationRequest
3
+ class AuthError < StandardError;end
4
+
5
+ URL = 'https://www.google.com/accounts/ClientLogin'
6
+
7
+ def initialize(email, password, opts={})
8
+ @email = email
9
+ @password = password
10
+ @account_type = opts.fetch(:account_type, 'HOSTED_OR_GOOGLE')
11
+ end
12
+
13
+ def parameters
14
+ {
15
+ 'Email' => @email,
16
+ 'Passwd' => @password,
17
+ 'accountType' => @account_type,
18
+ 'service' => 'analytics',
19
+ 'source' => 'vigetLabs-garb-001'
20
+ }
21
+ end
22
+
23
+ def uri
24
+ URI.parse(URL)
25
+ end
26
+
27
+ def send_request(ssl_mode)
28
+ http = Net::HTTP.new(uri.host, uri.port)
29
+ http.use_ssl = true
30
+ http.verify_mode = ssl_mode
31
+
32
+ if ssl_mode == OpenSSL::SSL::VERIFY_PEER
33
+ http.ca_file = CA_CERT_FILE
34
+ end
35
+
36
+ http.request(build_request) do |response|
37
+ raise AuthError unless response.is_a?(Net::HTTPOK)
38
+ end
39
+ end
40
+
41
+ def build_request
42
+ post = Net::HTTP::Post.new(uri.path)
43
+ post.set_form_data(parameters)
44
+ post
45
+ end
46
+
47
+ def auth_token(opts={})
48
+ ssl_mode = opts[:secure] ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
49
+ send_request(ssl_mode).body.match(/^Auth=(.*)$/)[1]
50
+ end
51
+
52
+ end
53
+ end
@@ -0,0 +1,42 @@
1
+ module Garb
2
+ class DataRequest
3
+ class ClientError < StandardError; end
4
+
5
+ def initialize(session, base_url, parameters={})
6
+ @session = session
7
+ @base_url = base_url
8
+ @parameters = parameters
9
+ end
10
+
11
+ def query_string
12
+ parameter_list = @parameters.map {|k,v| "#{k}=#{v}" }
13
+ parameter_list.empty? ? '' : "?#{parameter_list.join('&')}"
14
+ end
15
+
16
+ def uri
17
+ URI.parse(@base_url)
18
+ end
19
+
20
+ def send_request
21
+ response = if @session.single_user?
22
+ single_user_request(@session.auth_sub? ? 'AuthSub' : 'GoogleLogin')
23
+ elsif @session.oauth_user?
24
+ oauth_user_request
25
+ end
26
+
27
+ raise ClientError, response.body.inspect unless response.kind_of?(Net::HTTPSuccess)
28
+ response
29
+ end
30
+
31
+ def single_user_request(auth='GoogleLogin')
32
+ http = Net::HTTP.new(uri.host, uri.port)
33
+ http.use_ssl = true
34
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
35
+ http.get("#{uri.path}#{query_string}", 'Authorization' => "#{auth} #{auth == 'GoogleLogin' ? 'auth' : 'token'}=#{@session.auth_token}")
36
+ end
37
+
38
+ def oauth_user_request
39
+ @session.access_token.get("#{uri}#{query_string}")
40
+ end
41
+ end
42
+ end