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 = user.fb_user.stream[:posts]
return nil if posts.nil? or posts.empty?
streams = []
posts.each do |post|
stream = Stream.new
stream.message = post['message']
stream.time = Time.at(post['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
end
rescue
return "There were problems fetching the facebook streams"
end
end
end
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>
<div style="float:left;">
<%= fb_profile_pic(stream.uid) %>
</div>
<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>
</div>
</div>
<% 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: facebook, rubyonrails
