How to: fetch and show the user stream from facebook via facebook connect

This post assumes we are using the Facebooker plugin to Facebook Connect the Rails application to Facebook.

If you want an extended functionality of displaying a user’s stream on in your application, just the Facebook Connect is not going to work. It would be required that our app requests extended facebook permissions from the user.

Once the user allows our app to access the streams, we can code it in a modular way to display it like the twitter stream or so.

To keep the code neat and the functionality well placed in Rails app we can place this in a separate class.

Create a class facebook.rb and place it in the app/models directory and add the following code in it:

module Facebook
  class Stream
    attr_accessor :message, :uid, :published_at, :user

   def self.get(fb_user)
     posts =[:posts]
     return nil if posts.nil? or posts.empty?
     streams = []
     posts.each do |post|
        stream =
        stream.message = post['message']
        stream.time =['updated_time'].to_i)
        stream.uid = post['source_id']
        # if an existing user of rails app, we can connect more local functionality by uncommenting this line
        # stream.user = post['source_id'] ? User.find_by_fb_user_id(post['source_id']) : nil
        streams << stream
      return "There were problems fetching the facebook streams"


From the Controller get the streams

@streams = Facebook::Stream.get(facebook_session.user) if facebook_session

And in the view we can display the streams in twitter streams format like this

<% if @streams and !@streams.empty? %>
<%  @streams.each do |stream| %>
   <div style="float:left;">
     <%= fb_profile_pic(stream.uid) %>

   <div style="float:left" class='stream_messag'>
     <span class="name"><%= fb_name(stream.uid) %>:</span>
     <span class='message'><%= stream.message %></span>
     <p style="font-size: 12px"><%= distance_of_time_in_words_to_now(stream.published_at) %> ago</p>
<%  end %>
<% end %>

PS: If you don’t want the stream name or the stream photo to link to the facebook profile page, pass the linked boolean flag as 0 like this

  <%= fb_profile_pic(stream.uid, :linked => 0) %>
  <%= fb_name(stream.uid, :linked => 0) %>

Tags: ,
This entry was posted on Saturday, July 31st, 2010 at 5:08 am and is filed under facebook, rubyonrails. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Your comment