Using Koala in a Rails app, I need to obtain the total number of Facebook likes for dynamic pages.

For example, if there is a User model, I want to obtain the number of likes for each User's show page, and store this in a User.likes attribute.

I'm facing two challenges:

  1. The koala get_object method requires a Facebook UID. How can I obtain the UID for a page from its url?

  2. Using the Facebook open graph explorer, the hash does not appear to include the number of likes? How can I access the number of likes from the open graph?

有帮助吗?

解决方案

I eventually managed to solve both parts of this issue. In the end I abandoned Koala's get_object completely, and went directly to the open graph.

First, I needed to locate the open graph object representing the page of interest in my app. I found this at http://graph.facebook.com.?ids=http://my.app.com/user/xx.

This returned a json object, that I needed to parse.

Finally, I needed to access the correct key/value from the json object.

So putting this all together for my user model

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

I'm open to suggestions if there is a better way to do this

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top