2014-09-26 94 views
1

我很努力地訪問Google Contacts API。首先我嘗試了google-api-ruby-client gem,但事實證明它不支持Contacts API如何在ruby中訪問Google Contacts API

下一張照片是google_contacts_api gem。我使用oauth2來訪問驗證密鑰(Getting authentication token guide question)。但是,將令牌正確傳遞給API後,會產生錯誤。

`<main>': undefined method `[]' for #<GoogleContactsApi::GroupSet:0x000000039fcad8>` (NoMethodError). 

這是我的代碼。

# get token using oauth2 gem, and use it below in the google_contacts_api. 
google_contacts_user = GoogleContactsApi::User.new(token) 
contacts = google_contacts_user.contacts 
groups = google_contacts_user.groups 

# group methods 
group = groups[0] 
group.contacts 
puts group.contacts 

# contact methods 
puts contacts.count 
puts groups.count 
contact = contacts[0] 
contact.primary_email 
contact.emails 

我在做什麼錯?

UPDATE:

由於@alvin建議現在運轉。但小組聯繫人沒有被打印出來。相反,它是印刷#<GoogleContactsApi::ContactSet:0x000000020e49d8>。實例:

#<GoogleContactsApi::ContactSet:0x000000020e49d8> 
#<GoogleContactsApi::ContactSet:0x0000000504aec0> 
#<GoogleContactsApi::ContactSet:0x0000000518dfd0> 
#<GoogleContactsApi::ContactSet:0x000000052d9290> 
#<GoogleContactsApi::ContactSet:0x000000054280d8> 
#<GoogleContactsApi::ContactSet:0x0000000558c2f8> 
#<GoogleContactsApi::ContactSet:0x00000005746eb8> 
#<GoogleContactsApi::ContactSet:0x000000058a3ea0> 

我怎樣才能打印組聯繫人:這裏是什麼是這個代碼

groups = google_contacts_user.groups 

# group methods 
groups.each do |group| 
    group_contacts = group.contacts 
    puts group_contacts 
end 

輸出打印?

回答

2

編輯補充信息關於可枚舉實施

(我寫的寶石。)

有文件中的錯誤。 groupscontacts是實現Enumerable的類的實例,它不提供[]方法,但確實提供了first方法。

因此,請嘗試groups.first而不是groups[0]。同樣,使用contacts.first而不是contacts[0]。我的錯! (我可能在我的頭上做了to_a。)


響應更新

要回答這個問題的後半部分,它看起來像你找到相關的便捷方法ContactGroup,特別是Contact.primary_email方法。 See more methods in the (somewhat incomplete, sorry) YARD docs.

要獲取所有電子郵件,您基本上需要迭代返回的聯繫人。正如我在對問題第一部分的更新迴應中提到的,groupscontacts具有Enumerable的所有方法。 (Enumerable documentation)。下面是一些例子:

# What are all the groups called? 
user.groups.map(&:title) 

# Find group by title. (Returns nil if no such group.) 
group = user.groups.select { |g| g.title = "Group Name" } 

# Get all primary emails from a group 
group.contacts.map(&:primary_email) 

# Get all primary emails from all contacts regardless of group 
user.contacts.map(&:primary_email) 

你只需要使用Hashie::Mash方法來訪問數據時,不提供方便訪問(例如,如果谷歌開始返回額外的數據,創業板還沒有佔到還)。你描述的用例不需要這個。

P.S.將來,您可能希望開啓一個新問題,而不是編輯現有問題。