class PopularPages::RestClient

Public Class Methods

new() click to toggle source
# File lib/popular_pages/rest_client.rb, line 7
def initialize
  config = PopularPages::Configuration.new
  ENV['GOOGLE_PRIVATE_KEY'] = config.private_key
  ENV['GOOGLE_CLIENT_EMAIL'] = config.client_email
  ENV['GOOGLE_CLIENT_ID'] = config.client_id
end

Public Instance Methods

all(from = 7, to = 1) click to toggle source
# File lib/popular_pages/rest_client.rb, line 14
def all(from = 7, to = 1)
  url="#{ENV['GOOGLE_API_URL']}?ids=ga%3A#{ENV['GOOGLE_APPLICATION_ID']}&"\
  "start-date=#{from}daysAgo&end-date=#{to}daysAgo&metrics=ga%3AuniquePageviews&"\
  "dimensions=ga%3ApagePath&sort=-ga%3AuniquePageviews&max-results=200&"\
  "access_token=#{access_token}"

  uri = URI(url)
  res = Net::HTTP.get_response(uri)
  parse_response(res.body)
end

Private Instance Methods

access_token() click to toggle source
# File lib/popular_pages/rest_client.rb, line 27
def access_token
  authorization =
    Google::Auth.get_application_default(['https://www.googleapis.com/auth/analytics'])
  return unless authorization
  authorization.apply!({})
  authorization.access_token
end
parse_response(body) click to toggle source
# File lib/popular_pages/rest_client.rb, line 35
def parse_response(body)
  response = []
  body_hash = JSON.parse(body)
  return response unless body_hash['rows']

  body_hash['rows'].each do |row|
    response << { path: row[0], views: row[1] }
  end

  response
end