2013-11-20 58 views
1

我试图用这个Ruby Google Analytics API Dashing widget因为Ruby文件错误使用Ruby谷歌Analytics(分析)API

require 'google/api_client' 
require 'date' 


    # Update these to match your own apps credentials 
    service_account_email = '[YOUR SERVICE ACCOUNT EMAIL]' # Email of service account 
    key_file = 'path/to/your/keyfile.p12' # File containing your private key 
    key_secret = 'notasecret' # Password to unlock private key 
    profileID = '[YOUR PROFILE ID]' # Analytics profile ID. 

    # Get the Google API client 
    client = Google::APIClient.new(:application_name => '[YOUR APPLICATION NAME]', 
     :application_version => '0.01') 

    # Load your credentials for the service account 
    key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret) 
    client.authorization = Signet::OAuth2::Client.new(
     :token_credential_uri => 'https://accounts.google.com/o/oauth2/token', 
     :audience => 'https://accounts.google.com/o/oauth2/token', 
     :scope => 'https://www.googleapis.com/auth/analytics.readonly', 
     :issuer => service_account_email, 
     :signing_key => key) 

    # Start the scheduler 
    SCHEDULER.every '1m', :first_in => 0 do 

     # Request a token for our service account 
     client.authorization.fetch_access_token! 

     # Get the analytics API 
     analytics = client.discovered_api('analytics','v3') 

     # Start and end dates 
     startDate = DateTime.now.strftime("%Y-%m-01") # first day of current month 
     endDate = DateTime.now.strftime("%Y-%m-%d") # now 

     # Execute the query 
     visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => { 
     'ids' => "ga:" + profileID, 
     'start-date' => startDate, 
     'end-date' => endDate, 
     # 'dimensions' => "ga:month", 
     'metrics' => "ga:visitors", 
     # 'sort' => "ga:month" 
     }) 

     # Update the dashboard 
     send_event('visitor_count', { current: visitCount.data.rows[0][0] }) 
    end 

但是我收到错误Undefined method '[]' for nil:NilClass第二最后一行。任何人都可以点亮这里发生的事情吗?

编辑: 我现在知道visitCount.data是一个NIL对象的数组。是否有任何诊断可以执行,以确保API正确连接?任何人都可以提出这种情况发生的可能原因吗?

+0

'visitCount.data.rows'或'visitCount.data.rows [0]'返回'nil'。第一步是找出哪些,以及为什么。 –

+0

它看起来像visitCount.data.rows是一个数组对象和visitCount.data.rows [0]是一个NilClass对象 – user1893354

回答

2

流事件

if visitCount.data.rows[0].empty? 
    # assign some default 
    output = -1 
else 
    output = visitCount.data.rows[0][0] 
end 

# Update the dashboard 
send_event('visitor_count', { current: output }) 
+0

我试过这个,它返回相同的错误,这意味着visitCount不是零。然而,根据我的评论,visitCount.data.rows [0]是一个零对象。 – user1893354

+0

上面那个用空的怎么样? – sam

0

OK事实证明,我被赋予了不正确的个人资料ID之前试试这个。没有错误表明“此配置文件ID不存在”这种说法有些令人惊讶。那样会更有帮助。无论如何,我现在有正确的配置文件ID,它的工作原理。如果有人想知道,要找到配置文件ID,请导航至您感兴趣的分析配置文件,并且网址的末尾有类似pXXXXXXXX的地方,其中X是您的配置文件ID。

相关问题