2014-09-26 75 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.将来,您可能希望开启一个新问题,而不是编辑现有问题。

相关问题