Class: GoogleAnalyticsFeeds::Session

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

Overview

A Google Analytics session, used to retrieve reports.

Instance Method Summary collapse

Constructor Details

#initialize(connection = Faraday.default_connection) ⇒ Session

Creates a new session.

Optionally pass a Faraday connection, otherwise uses the default Faraday connection.



28
29
30
# File 'lib/google_analytics_feeds.rb', line 28

def initialize(connection=Faraday.default_connection)
  @connection = connection
end

Instance Method Details

#fetch_report(report, handler = nil, &block) ⇒ Object

Retrieve a report from Google Analytics.

Rows are yielded to a RowHandler, provided either as a class, instance or a block.



55
56
57
58
59
60
61
62
63
64
# File 'lib/google_analytics_feeds.rb', line 55

def fetch_report(report, handler=nil, &block)
  handler  = block if handler.nil?
  response = report.retrieve(@token, @connection)

  if response.success?
    DataFeedParser.new(handler).parse_rows(StringIO.new(response.body))
  else
    raise HttpError.new
  end
end

#login(username, password) ⇒ Object

Log in to Google Analytics with username and password

This should be done before attempting to fetch any reports.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/google_analytics_feeds.rb', line 35

def (username, password)
  return @token if @token
  response = @connection.post(CLIENT_LOGIN_URI,
                              'Email'       => username,
                              'Passwd'      => password,
                              'accountType' => 'HOSTED_OR_GOOGLE',
                              'service'     => 'analytics',
                              'source'      => 'ruby-google-analytics-feeds')

  if response.success?
    @token = response.body.match(/^Auth=(.*)$/)[1]
  else
    raise AuthenticationError
  end
end