Class: GAAPI::Query

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

Instance Method Summary collapse

Constructor Details

#initialize(query_string, view_id, access_token, start_date, end_date) ⇒ Query

Create a Query object.

Parameters:

  • access_token (String)

    A valid access token with which to make a request to the specified View ID.

  • end_date (Date, String)

    The end date for the report.

  • query_string (String, Hash, JSON)

    The query in JSON format.

  • start_date (Date, String)

    The start date for the report.

  • view_id (String)

    The view ID of the property for which to submit the query.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/gaapi/query.rb', line 16

def initialize(query_string, view_id, access_token, start_date, end_date)
  @access_token = access_token.to_s
  query_string = JSON.parse(query_string) unless query_string.is_a?(Hash)
  @query = stringify_keys(query_string)
  @query["reportRequests"] = @query["reportRequests"].map do |report_request|
    report_request["viewId"] = view_id
    report_request["dateRanges"] = [
      "startDate": start_date.to_s,
      "endDate": end_date.to_s
    ]
    report_request["pageSize"] ||= 10_000
    report_request
  end
  # puts "query: #{JSON.pretty_generate(query)}"
end

Instance Method Details

#executeGAAPI::Response

Send the requested query to Google Analytics and return the response.

Returns:



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/gaapi/query.rb', line 34

def execute
  uri = URI.parse("https://analyticsreporting.googleapis.com/v4/reports:batchGet")
  https = Net::HTTP.new(uri.host, uri.port)
  https.use_ssl = true
  # https.set_debug_output($stdout)
  request = Net::HTTP::Post.new(uri.request_uri,
    "Content-Type" => "application/json",
    "Authorization" => "Bearer #{access_token}")
  request.body = query.to_json
  Response.new(https.request(request))
end