0

在 Rails 应用程序中使用 Koala,我需要获取动态页面的 Facebook 喜欢总数。

例如,如果有一个 User 模型,我想获取每个 User 的显示页面的点赞数,并将其存储在 User.likes 属性中。

我面临两个挑战:

  1. koalaget_object方法需要 Facebook UID。如何从其 url 获取页面的 UID?

  2. 使用 Facebook 开放图形浏览器,哈希似乎不包括点赞数?如何从打开的图表中访问喜欢的数量?

4

1 回答 1

0

我最终设法解决了这个问题的两个部分。最后我彻底放弃了考拉的get_object,直接上open graph。

首先,我需要在我的应用程序中找到代表感兴趣页面的打开图形对象。我在http://graph.facebook.com.?ids=http://my.app.com/user/xx.

这返回了一个我需要解析的 json 对象。

最后,我需要从 json 对象中访问正确的键/值。

所以把这一切放在我的用户模型中

class User
  def facebook_likes
    user_url = UrlGenerator.new.user_url(self)  
    #UrlGenerator is a custom module that allows  
    #access to Rails route helpers in the model, 
    #no doubt some will consider this bad practice but
    #in this case I believe it is justified
    graph_url = "https://graph.facebook.com/?ids=#{user_url}"
    graph_object = JSON.parse( open( graph_url ).read )
    likes = graph_object["#{UrlGenerator.new.candidate_url(self)}"]["shares"] || 0 #returns 0 if no likes found
  end
end

如果有更好的方法,我愿意接受建议

于 2014-01-17T12:41:06.280 回答