simple_analytics 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ *.gem
2
+ .bundle
3
+ vendor/bundle
4
+ bin
5
+ pkg/*
6
+
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source 'http://rubygems.org'
2
+
3
+ group :test do
4
+ gem "rake", "~> 0.9.2.2"
5
+ end
6
+
7
+ # Specify your gem's dependencies in simple_analytics.gemspec
8
+ gemspec
@@ -0,0 +1,43 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ simple_analytics (0.0.1)
5
+ google_client_login (~> 0.3.1)
6
+ json
7
+
8
+ GEM
9
+ remote: http://rubygems.org/
10
+ specs:
11
+ addressable (2.2.6)
12
+ crack (0.3.1)
13
+ diff-lcs (1.1.3)
14
+ fuubar (0.0.6)
15
+ rspec (~> 2.0)
16
+ rspec-instafail (~> 0.1.8)
17
+ ruby-progressbar (~> 0.0.10)
18
+ google_client_login (0.3.1)
19
+ json (1.6.5)
20
+ rake (0.9.2.2)
21
+ rspec (2.8.0)
22
+ rspec-core (~> 2.8.0)
23
+ rspec-expectations (~> 2.8.0)
24
+ rspec-mocks (~> 2.8.0)
25
+ rspec-core (2.8.0)
26
+ rspec-expectations (2.8.0)
27
+ diff-lcs (~> 1.1.2)
28
+ rspec-instafail (0.1.9)
29
+ rspec-mocks (2.8.0)
30
+ ruby-progressbar (0.0.10)
31
+ webmock (1.7.10)
32
+ addressable (~> 2.2, > 2.2.5)
33
+ crack (>= 0.1.7)
34
+
35
+ PLATFORMS
36
+ ruby
37
+
38
+ DEPENDENCIES
39
+ fuubar (~> 0.0.6)
40
+ rake (~> 0.9.2.2)
41
+ rspec (~> 2.8)
42
+ simple_analytics!
43
+ webmock (~> 1.7.10)
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2012 Andrew Djoga
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,75 @@
1
+ = SimpleAnalytics
2
+
3
+ SimpleAnalytics gem provides accessing Google Analytics Export Api. It uses Version 3.0 of the Google Core Reporting API with JSON. You can find the google documentation {here}[http://code.google.com/apis/analytics/docs/gdata/v3/gdataGettingStarted.html].
4
+
5
+ == Installation
6
+
7
+ Install as a gem from rubygems:
8
+
9
+ gem install simple_analytics
10
+
11
+ == Getting Started
12
+
13
+ Authentication:
14
+
15
+ analytics = SimpleAnalytics::Api.authenticate('user@gmail.com', 'password')
16
+
17
+ The <tt>authenticate</tt> method sets an <tt>auth_token</tt> in the analytics service object. Then you can fetch data:
18
+
19
+ analytics.fetch('ids' => 'ga:id',
20
+ 'metrics' => 'ga:visitors',
21
+ 'dimensions' => 'ga:country',
22
+ 'start-date' => '2012-01-01',
23
+ 'end-date' => '2012-01-10')
24
+ # => [["United States","24451"], ["Brazil","15616"], ["Spain","3966"]
25
+
26
+ The <tt>fetch</tt> method sets and returns rows. Required query parameters are used to configure which data to return from Google Analytics:
27
+ * ids — The profile IDs from which to access data.
28
+ * start-date — The beginning of the date range.
29
+ * end-date — The end of the date range.
30
+ * metrics — The numeric values to return.
31
+
32
+ For more detailed information about the parameters see {google REST docs}[http://code.google.com/apis/analytics/docs/gdata/v3/exportRest.html].
33
+
34
+ == Authentication
35
+
36
+ For the authentication it uses gem {google_client_login}[https://github.com/fortuity/google_client_login] based on the ClientLogin. You can also pass extra parameters which allows the gem (see the gem's {README}[https://github.com/fortuity/google_client_login]):
37
+
38
+ analytics = SimpleAnalytics::Api.authenticate('user@gmail.com', 'password', { :accountType => 'GOOGLE',
39
+ :source => 'company-app-version' })
40
+
41
+ ==== Authentication Token
42
+
43
+ You can set yourself the <tt>auth_token</tt> to use it in the fetching:
44
+
45
+ analytics.auth_token = 'your-token-from-oauth'
46
+
47
+ == An example
48
+
49
+ All parameters are escaped before a request. For date you can use the next tip: <tt>your_date.strftime("%Y-%m-%d")</tt>.
50
+
51
+ analytics = SimpleAnalytics::Api.authenticate('user@gmail.com', 'password')
52
+
53
+ analytics.fetch('ids' => 'ga:id',
54
+ 'metrics' => 'ga:visitors',
55
+ 'dimensions' => 'ga:country',
56
+ 'start-date' => '2012-01-01',
57
+ 'end-date' => '2012-01-10')
58
+ # => [["United States","24451"], ["Brazil","15616"], ["Spain","3966"]
59
+
60
+ analytics.rows
61
+ # => [["United States","24451"], ["Brazil","15616"], ["Spain","3966"]
62
+
63
+ analytics.body
64
+ # => returns the parsed response body (hash), where you can get other info, see google docs
65
+
66
+ analytics.fetch('ids' => 'ga:another-id',
67
+ 'metrics' => 'ga:visitors,ga:newVisits',
68
+ 'dimensions' => 'ga:pagePath',
69
+ 'filters' => 'ga:pagepath=~/articles/[\w-]+\z'
70
+ 'start-date' => '2012-01-01',
71
+ 'end-date' => '2012-01-10')
72
+ # => [["/article/first-post","12", "2"], ["/article/second-post","2", "1"]]
73
+
74
+ analytics.rows
75
+ # => [["/article/first-post","12", "2"], ["/article/second-post","2", "1"]]
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
3
+ require "rspec/core/rake_task"
4
+
5
+ RSpec::Core::RakeTask.new(:spec)
6
+ task :default => [:spec]
@@ -0,0 +1,77 @@
1
+ require 'simple_analytics/version'
2
+ require 'json'
3
+ require 'google_client_login'
4
+
5
+ module SimpleAnalytics
6
+ # Required query parameters are used to configure which data to return from Google Analytics.
7
+ REQUIRED_PROPERTIES = ['ids', 'start-date', 'end-date', 'metrics']
8
+
9
+ class NotSuccessfulResponseError < RuntimeError; end
10
+
11
+ class Api
12
+ # An authentication token for the Google Analytics Api.
13
+ attr_accessor :auth_token
14
+
15
+ # +rows+ is a 2-dimensional array of strings, each string represents a value in the table.
16
+ # +body+ is the data in response body.
17
+ attr_reader :rows, :body
18
+
19
+ # Authentication using ClientLogin, returns an analytics service object.
20
+ def self.authenticate(username, password, options = {})
21
+ new(username, password, options).tap do |analytics|
22
+ analytics.authenticate
23
+ end
24
+ end
25
+
26
+ def initialize(username, password, options = {})
27
+ @username = username
28
+ @password = password
29
+ @options = options
30
+ end
31
+
32
+ # Authenticates using ClientLogin.
33
+ def authenticate
34
+ login_service = ::GoogleClientLogin::GoogleAuth.new(client_options)
35
+ login_service.authenticate(@username, @password, @options[:captcha_response])
36
+ @auth_token = login_service.auth
37
+ end
38
+
39
+ # Fetches the report data, the following query parameters are required: 'ids', 'start-date', 'end-date', 'metrics'.
40
+ def fetch(properties)
41
+ check_properties(properties)
42
+
43
+ uri = URI.parse("https://www.googleapis.com/analytics/v3/data/ga")
44
+ http = Net::HTTP.new(uri.host, uri.port)
45
+ http.use_ssl = true
46
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
47
+
48
+ response = http.get("#{uri.path}?#{query_string(properties)}", { 'Authorization' => "GoogleLogin auth=#{@auth_token}", 'GData-Version' => '3' })
49
+ raise NotSuccessfulResponseError.new, response.body if response.code_type != Net::HTTPOK
50
+ @body = JSON.parse(response.body)
51
+ @rows = @body['rows']
52
+ end
53
+
54
+ private
55
+
56
+ def client_options
57
+ { :service => 'analytics',
58
+ :accountType => (@options[:accountType] || 'GOOGLE'),
59
+ :source => (@options[:source] || 'djo-simple_analytics-001') }
60
+ end
61
+
62
+ def check_properties(properties)
63
+ required = properties.keys.map(&:to_s) & REQUIRED_PROPERTIES
64
+ if required.size != REQUIRED_PROPERTIES.size
65
+ raise ArgumentError, "Properties: #{REQUIRED_PROPERTIES.join(', ')} are required."
66
+ end
67
+ end
68
+
69
+ def query_string(properties)
70
+ properties.map{ |k, v| "#{k}=#{escape v}" }.sort.join('&')
71
+ end
72
+
73
+ def escape(property)
74
+ URI.escape(property.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,3 @@
1
+ module SimpleAnalytics
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,23 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/simple_analytics/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Andrew Djoga"]
6
+ gem.email = ["andrew.djoga@gmail.com"]
7
+ gem.description = %q{The Simple Analytics allows to access Google Analytics report data}
8
+ gem.summary = %q{Google Analytics Export API Ruby Wrapper}
9
+ gem.homepage = "https://github.com/Djo/simple_analytics"
10
+
11
+ gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
12
+ gem.files = `git ls-files`.split("\n")
13
+ gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
14
+ gem.name = "simple_analytics"
15
+ gem.require_paths = ["lib"]
16
+ gem.version = SimpleAnalytics::VERSION
17
+
18
+ gem.add_dependency "json"
19
+ gem.add_dependency "google_client_login", "~> 0.3.1"
20
+ gem.add_development_dependency "rspec", "~> 2.8"
21
+ gem.add_development_dependency "fuubar", "~> 0.0.6"
22
+ gem.add_development_dependency "webmock", "~> 1.7.10"
23
+ end
@@ -0,0 +1,68 @@
1
+ require 'spec_helper'
2
+
3
+ describe SimpleAnalytics::Api do
4
+ before do
5
+ @auth_request = stub_request(:post, "https://www.google.com/accounts/ClientLogin").
6
+ with(:body => { "accountType" => "GOOGLE", "source" => "djo-simple_analytics-001", "service" => "analytics", "Email"=>"user@gmail.com", "Passwd" => "password" }).
7
+ to_return(:status => 200, :body => "AUTH=secret\n")
8
+ end
9
+
10
+ describe ".authenticate" do
11
+ it "requests authentication" do
12
+ SimpleAnalytics::Api.authenticate('user@gmail.com', 'password')
13
+ @auth_request.should have_been_requested
14
+ end
15
+
16
+ it "fetches an auth token" do
17
+ analytics = SimpleAnalytics::Api.authenticate('user@gmail.com', 'password')
18
+ analytics.auth_token.should eq('secret')
19
+ end
20
+ end
21
+
22
+ describe "#fetch" do
23
+ before { stub_analytics_request }
24
+
25
+ let(:analytics) { SimpleAnalytics::Api.authenticate('user@gmail.com', 'password') }
26
+ let(:properties) { { 'ids' => 'ga:id',
27
+ 'metrics' => 'ga:visitors',
28
+ 'dimensions' => 'ga:country',
29
+ 'start-date' => '2012-01-01',
30
+ 'end-date' => '2012-01-10' } }
31
+
32
+ it "raises an argument error without requried properties" do
33
+ expect {
34
+ analytics.fetch('ids' => 'ga:xxx')
35
+ }.to raise_error(ArgumentError)
36
+ end
37
+
38
+ it "fetches rows" do
39
+ rows = analytics.fetch(properties)
40
+ rows.should eq([[ "United States", "73834"], ["Ukraine", "15726"]])
41
+ analytics.rows.should eq([[ "United States", "73834"], ["Ukraine", "15726"]])
42
+ end
43
+
44
+ it "sets column headers" do
45
+ rows = analytics.fetch(properties)
46
+ rows.should eq([[ "United States", "73834"], ["Ukraine", "15726"]])
47
+ analytics.rows.should eq([[ "United States", "73834"], ["Ukraine", "15726"]])
48
+ end
49
+
50
+ it "raises not successful response error" do
51
+ stub_analytics_request(:status => 403, :code_type => Net::HTTPForbidden)
52
+
53
+ expect {
54
+ analytics.fetch(properties)
55
+ }.to raise_error(SimpleAnalytics::NotSuccessfulResponseError)
56
+ end
57
+
58
+ def stub_analytics_request(response = {})
59
+ data = { :body => { :rows => [[ "United States", "73834"], ["Ukraine", "15726"]] }.to_json,
60
+ :status => 200,
61
+ :code_type => Net::HTTPOK }.merge(response)
62
+
63
+ stub_request(:get, "https://www.googleapis.com/analytics/v3/data/ga?dimensions=ga:country&end-date=2012-01-10&ids=ga:id&metrics=ga:visitors&start-date=2012-01-01").
64
+ with(:headers => { 'Authorization'=>'GoogleLogin auth=secret', 'Gdata-Version'=>'3' }).
65
+ to_return(data)
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,4 @@
1
+ require 'rubygems'
2
+ require 'bundler/setup'
3
+ require 'webmock/rspec'
4
+ require 'simple_analytics'
metadata ADDED
@@ -0,0 +1,119 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: simple_analytics
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Andrew Djoga
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-02-01 00:00:00.000000000Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: json
16
+ requirement: &70098909002660 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: *70098909002660
25
+ - !ruby/object:Gem::Dependency
26
+ name: google_client_login
27
+ requirement: &70098908994280 !ruby/object:Gem::Requirement
28
+ none: false
29
+ requirements:
30
+ - - ~>
31
+ - !ruby/object:Gem::Version
32
+ version: 0.3.1
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: *70098908994280
36
+ - !ruby/object:Gem::Dependency
37
+ name: rspec
38
+ requirement: &70098908993300 !ruby/object:Gem::Requirement
39
+ none: false
40
+ requirements:
41
+ - - ~>
42
+ - !ruby/object:Gem::Version
43
+ version: '2.8'
44
+ type: :development
45
+ prerelease: false
46
+ version_requirements: *70098908993300
47
+ - !ruby/object:Gem::Dependency
48
+ name: fuubar
49
+ requirement: &70098908992220 !ruby/object:Gem::Requirement
50
+ none: false
51
+ requirements:
52
+ - - ~>
53
+ - !ruby/object:Gem::Version
54
+ version: 0.0.6
55
+ type: :development
56
+ prerelease: false
57
+ version_requirements: *70098908992220
58
+ - !ruby/object:Gem::Dependency
59
+ name: webmock
60
+ requirement: &70098908990640 !ruby/object:Gem::Requirement
61
+ none: false
62
+ requirements:
63
+ - - ~>
64
+ - !ruby/object:Gem::Version
65
+ version: 1.7.10
66
+ type: :development
67
+ prerelease: false
68
+ version_requirements: *70098908990640
69
+ description: The Simple Analytics allows to access Google Analytics report data
70
+ email:
71
+ - andrew.djoga@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - .gitignore
77
+ - Gemfile
78
+ - Gemfile.lock
79
+ - LICENSE
80
+ - README.rdoc
81
+ - Rakefile
82
+ - lib/simple_analytics.rb
83
+ - lib/simple_analytics/version.rb
84
+ - simple_analytics.gemspec
85
+ - spec/simple_analytics_spec.rb
86
+ - spec/spec_helper.rb
87
+ homepage: https://github.com/Djo/simple_analytics
88
+ licenses: []
89
+ post_install_message:
90
+ rdoc_options: []
91
+ require_paths:
92
+ - lib
93
+ required_ruby_version: !ruby/object:Gem::Requirement
94
+ none: false
95
+ requirements:
96
+ - - ! '>='
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ segments:
100
+ - 0
101
+ hash: -2303643778759929262
102
+ required_rubygems_version: !ruby/object:Gem::Requirement
103
+ none: false
104
+ requirements:
105
+ - - ! '>='
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ segments:
109
+ - 0
110
+ hash: -2303643778759929262
111
+ requirements: []
112
+ rubyforge_project:
113
+ rubygems_version: 1.8.10
114
+ signing_key:
115
+ specification_version: 3
116
+ summary: Google Analytics Export API Ruby Wrapper
117
+ test_files:
118
+ - spec/simple_analytics_spec.rb
119
+ - spec/spec_helper.rb