2013-11-20 96 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。

相關問題