Module: Garb::Resource

Included in:
Bounces, Exits, Report, Pageviews, UniquePageviews, Visits
Defined in:
lib/garb/resource.rb

Constant Summary collapse

MONTH =
2592000
URL =
"https://www.google.com/analytics/feeds/data"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



6
7
8
9
10
11
12
13
# File 'lib/garb/resource.rb', line 6

def self.extended(base)
  # define a method on a module that gets included into profile
  # Exits would make:
  # to enable profile.exits(options_hash, &block)
  # returns Exits.results(self, options_hash, &block)
  # every class defined which extends Resource will add to the module
  ProfileReports.add_report_method(base)
end

Instance Method Details

#clear_filtersObject



39
40
41
# File 'lib/garb/resource.rb', line 39

def clear_filters
  @filter_parameters = FilterParameters.new
end

#default_paramsObject



64
65
66
67
68
# File 'lib/garb/resource.rb', line 64

def default_params
  {'ids' => @profile.table_id,
    'start-date' => format_time(@start_date),
    'end-date' => format_time(@end_date)}
end

#filters(*hashes, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/garb/resource.rb', line 28

def filters(*hashes, &block)
  @filter_parameters ||= FilterParameters.new

  hashes.each do |hash|
    @filter_parameters.parameters << hash
  end

  @filter_parameters.filters(&block) if block_given?
  @filter_parameters
end

#format_time(t) ⇒ Object



82
83
84
# File 'lib/garb/resource.rb', line 82

def format_time(t)
  t.strftime('%Y-%m-%d')
end

#page_paramsObject



60
61
62
# File 'lib/garb/resource.rb', line 60

def page_params
  {'max-results' => @limit, 'start-index' => @offset}.reject{|k,v| v.nil?}
end

#paramsObject



70
71
72
73
74
75
76
77
78
79
80
# File 'lib/garb/resource.rb', line 70

def params
  [
    metrics.to_params,
    dimensions.to_params,
    sort.to_params,
    filters.to_params,
    page_params
  ].inject(default_params) do |p, i|
    p.merge(i)
  end
end

#results(profile, opts = {}, &block) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/garb/resource.rb', line 43

def results(profile, opts = {}, &block)
  @profile = profile.is_a?(Profile) ? profile : Profile.first(profile, opts.fetch(:session, Session))

  if @profile
    @start_date = opts.fetch(:start_date, Time.now - MONTH)
    @end_date = opts.fetch(:end_date, Time.now)
    @limit = opts.fetch(:limit, nil)
    @offset = opts.fetch(:offset, nil)

    instance_eval(&block) if block_given?

    ReportResponse.new(send_request_for_body).results
  else
    []
  end
end

#send_request_for_bodyObject



86
87
88
89
90
# File 'lib/garb/resource.rb', line 86

def send_request_for_body
  request = DataRequest.new(@profile.session, URL, params)
  response = request.send_request
  response.body
end