Class: LazyGoogleAnalytics::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/lazy_google_analytics/client.rb

Constant Summary collapse

CLIENT_OPTIONS =
%w(api_method parameters ids start_date end_date dimensions metrics sort filters)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Client

Returns a new instance of Client.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/lazy_google_analytics/client.rb', line 7

def initialize(opts = {})

  @auth ||= LazyGoogleAnalytics::Auth.new
  @auth.authorize # check expiration and cache ?

  self.tap do |client|
    client.options    ||= {}
    client.defaults_options(opts)
    client.options ||= opts
    yield client if block_given?
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, opts = {}) ⇒ Object



58
59
60
# File 'lib/lazy_google_analytics/client.rb', line 58

def method_missing(meth, opts = {})
  merge_options meth, opts
end

Instance Attribute Details

#authObject

Returns the value of attribute auth.



5
6
7
# File 'lib/lazy_google_analytics/client.rb', line 5

def auth
  @auth
end

#optionsObject

Returns the value of attribute options.



5
6
7
# File 'lib/lazy_google_analytics/client.rb', line 5

def options
  @options
end

Instance Method Details

#defaults_options(opts) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/lazy_google_analytics/client.rb', line 20

def defaults_options(opts)

  api_method = opts[:api_method] ||= @auth.analytics.data.ga.get
  start_date = opts[:start_date] ||= DateTime.now.prev_month.strftime("%Y-%m-%d")
  end_date   = opts[:end_date]   ||= DateTime.now.strftime("%Y-%m-%d")
  ids        = opts[:ids]        ||= "ga:#{LazyGoogleAnalytics::Config.profile_id}"
  dimensions = opts[:dimensions] ||= "ga:day,ga:month"
  metrics    = opts[:metrics]    ||= "ga:visits"
  sort       = opts[:sort]       ||= "ga:month,ga:day"

  self.api_method(api_method)
  self.parameters({'ids' => ids,
                  'start-date' => start_date,
                  'end-date' => end_date,
                  'dimensions' => dimensions,
                  'metrics' => metrics,
                  'sort' => sort })
end

#formatted_columnsObject



46
47
48
49
50
# File 'lib/lazy_google_analytics/client.rb', line 46

def formatted_columns
  (@results || self.results).data.column_headers.map { |c|
    c.name
  }.join("\t")
end

#formatted_rowsObject



52
53
54
55
56
# File 'lib/lazy_google_analytics/client.rb', line 52

def formatted_rows
  (@results || self.results).data.rows.each do |r|
    print r.join("\t"), "\n"
  end
end

#resultsObject



40
41
42
43
44
# File 'lib/lazy_google_analytics/client.rb', line 40

def results
  @results = @auth.client.execute(@options)
  raise_detected_errors if @results.status > 200
  @results
end