Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Cleanups, custom errors and more.

  • Loading branch information...
commit 6ab23898f1f1bbc8bcbe126ad71fb8452702c09b 1 parent 9c84dca
@Sija authored
View
2  lib/garb/management/feed.rb
@@ -1,7 +1,7 @@
module Garb
module Management
class Feed
- BASE_URL = "https://www.googleapis.com/analytics/v3/management"
+ BASE_URL = 'https://www.googleapis.com/analytics/v3/management'
attr_reader :request
View
2  lib/garb/management/profile.rb
@@ -28,7 +28,7 @@ def initialize(entry, session)
end
def goals
- Goal.for_profile(self)
+ Goal.for_profile self
end
end
end
View
24 lib/garb/model.rb
@@ -1,8 +1,8 @@
module Garb
module Model
MONTH = 2592000
- #URL = "https://www.google.com/analytics/feeds/data"
- URL = "https://www.googleapis.com/analytics/v3/data/ga"
+ #URL = 'https://www.google.com/analytics/feeds/data'
+ URL = 'https://www.googleapis.com/analytics/v3/data/ga'
def self.extended(base)
ProfileReports.add_report_method(base)
@@ -27,9 +27,8 @@ def instance_klass
end
def results(profile, options = {})
- if options.delete(:all)
- return all(profile, options)
- end
+ return self.all(profile, options) if options.delete(:all)
+
start_date = options.fetch(:start_date, Time.now - MONTH)
end_date = options.fetch(:end_date, Time.now)
default_params = build_default_params(profile, start_date, end_date)
@@ -43,7 +42,6 @@ def results(profile, options = {})
parse_sort(options).to_params,
build_page_params(options)
]
-
data = send_request_for_data(profile, build_params(param_set))
ReportResponse.new(data, instance_klass).results
end
@@ -51,11 +49,15 @@ def results(profile, options = {})
def all(profile, options = {})
limit = options.delete(:limit)
options[:limit] = 10_000 # maximum allowed
- results = []
- while ((rs = results(profile, options).to_a) && !rs.empty?)
- results.concat rs
- break if limit and results.size >= limit
+ results = nil
+ while ((rs = results(profile, options)) && !rs.empty?)
+ results \
+ ? results.concat(rs.to_a)
+ : results = rs
options[:offset] = results.size
+
+ break if limit and results.size >= limit
+ break if results.size >= results.total_results
end
limit ? results[0...limit] : results
end
@@ -68,7 +70,7 @@ def send_request_for_data(profile, params)
end
def build_params(param_set)
- param_set.inject({}) { |p,i| p.merge(i) }.reject { |k,v| v.nil? }
+ param_set.inject({}) { |p,i| p.merge i }.reject { |k,v| v.nil? }
end
def parse_filters(options)
View
46 lib/garb/report_response.rb
@@ -2,26 +2,32 @@ module Garb
class ReportResponse
def initialize(response_body, instance_klass = OpenStruct)
- @data = response_body
+ @response_body = response_body
@instance_klass = instance_klass
end
def results
if @results.nil?
- if defined?(Rails) and Rails.logger
- Rails.logger.debug "Garb::ReportResponse -> #{parsed_data.inspect}"
- end
@results = ResultSet.new(parse)
- @results.total_results = parse_total_results
- @results.sampled = parse_sampled_flag
+ @results.total_results = total_results
+ @results.sampled = sampled?
end
@results
end
+ def total_results
+ data[:total_results].to_i
+ end
+
def sampled?
+ data[:contains_sampled_data] != 'false'
end
private
+ def keys
+ @keys ||= column_headers.map { |header| Garb.from_ga header['name'] }
+ end
+
def parse
rows.map do |row|
@instance_klass.new(Hash[*keys.zip(row).flatten])
@@ -29,27 +35,23 @@ def parse
end
def column_headers
- parsed_data['columnHeaders']
- end
-
- def keys
- column_headers.map { |header| Garb.from_ga(header['name']) }
+ data[:column_headers] || []
end
def rows
- parsed_data['rows'] || []
- end
-
- def parse_total_results
- parsed_data['totalResults'].to_i
+ data[:rows] || []
end
- def parse_sampled_flag
- parsed_data['containsSampledData']
- end
-
- def parsed_data
- @parsed_data ||= JSON.parse(@data)
+ def data
+ unless @data
+ @data = JSON.parse @response_body
+ @data = @data.inject({}) do |data, pair|
+ key, value = pair
+ data[key.underscore.to_sym] = value
+ data
+ end
+ end
+ @data
end
end
end
View
33 lib/garb/request/data.rb
@@ -2,16 +2,20 @@ module Garb
class ClientError < StandardError
attr_reader :code, :message, :errors
- def initialize(code, message, errors = [])
+ def initialize(message, code = nil, errors = [])
@code, @message, @errors = code, message, errors
end
end
+ class BadRequestError < ClientError; end
+ class InvalidCredentialsError < ClientError; end
+ class InsufficientPermissionsError < ClientError; end
+ class BackendError < ClientError; end
module Request
class Data
- attr_writer :format
-
def initialize(session, base_url, parameters = {})
+ parameters.merge!('key' => Garb.api_key) unless Garb.api_key.nil?
+
@session = session
@base_url = base_url
@parameters = parameters
@@ -22,23 +26,17 @@ def parameters
end
def query_string
- parameters.merge!('key' => Garb.api_key) unless Garb.api_key.nil?
- parameters.merge!('alt' => format)
parameter_list = parameters.map { |k,v| "#{k}=#{v}" }
parameter_list.empty? ? '' : "?#{parameter_list.join('&')}"
end
- def format
- @format ||= 'json' # TODO Support other formats?
- end
-
def uri
@uri ||= URI.parse(@base_url)
end
def send_request
- if defined?(Rails) and Rails.logger
- Rails.logger.debug "Garb::Request -> #{uri.path}#{query_string}"
+ if defined?(Rails) and Rails.env == 'development'
+ Rails.logger.try :debug, "Garb::Request -> #{uri.path}#{query_string}"
end
response = if @session.single_user?
@@ -49,10 +47,17 @@ def send_request
unless response.kind_of?(Net::HTTPSuccess) || (response.respond_to?(:status) && response.status == 200)
body = JSON.parse(response.body) rescue nil
- if body
- raise ClientError.new(body['error']['code'], body['error']['code'], body['error']['errors'])
+ if body and error = body['error']
+ klass = case error['code']
+ when 400 then BadRequestError
+ when 401 then InvalidCredentialsError
+ when 403 then InsufficientPermissionsError
+ when 503 then BackendError
+ else ClientError
+ end
+ raise klass.new(error['message'], error['code'], error['errors'])
else
- raise ClientError, response.body.inspect
+ raise ClientError, response ? response.body.inspect : nil
end
end
response
View
20 lib/garb/result_set.rb
@@ -1,21 +1,21 @@
module Garb
class ResultSet
include Enumerable
+ extend Forwardable
- attr_accessor :total_results, :sampled
-
- alias :sampled? :sampled
+ attr_accessor :results, :total_results, :sampled
+ alias_method :sampled?, :sampled
+
+ def_delegators :results, :each, :concat, :to_a, :count, :size, :empty?
def initialize(results)
@results = results
end
-
- def each(&block)
- @results.each(&block)
- end
-
- def to_a
- @results
+
+ def [](*args)
+ copy = self.dup
+ copy.results = @results[*args]
+ copy
end
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.