How to: implement the simplest way to fetch friends timeline streams from Twitter in Ruby on Rails

If you don’t want the Rails application to connect to the Twitter using OAUTH and just want to display the user’s timeline it can be done in a very simple way using Twitter HTTP authentication.

Add two fields in the users table:

  • twitter_username
  • twitter_password

After the user provides these two values the tweets from friends can be shown very easily.

Install the twitter gem

sudo gem install twitter

Update your config/environment.rb with the following:

config.gem "twitter", :version => '0.9.8'
config.gem "oauth", :version => "0.4.1"
config.gem "hashie", :version => "0.2.2"
config.gem "httparty", :version => "0.5.2"
config.gem "yajl-ruby", :version => "0.7.7"

Now to keep the code neat and well placed, create a file app/models/stream.rb and add the following code:

require 'twitter'
class Stream

attr_accessor :id, :user, :name, :message, :photo, :created_at
class << self

  def twitter_friends_stream(user)
      return nil if user.twitter_username.blank? or user.twitter_password.blank?
      httpauth =, user.twitter_password)
      client =
      timelines = client.friends_timeline
      return nil unless timelines.is_a?(Array)
      streams = []
      timelines.each do |timeline|
        stream =
        stream.message = timeline.text ="_twitter"
        stream.time = timeline.created_at = (timeline.user.screen_name rescue nil)
        # if timeline.user.profile_image_url is nil, you can add your application's custom default image = (timeline.user.profile_image_url rescue nil)
        stream.user = ? User.find_by_twitter( : nil
        streams << stream
      return nil



In controller you can fetch the streams for the user as:

@streams = Stream.twitter_friends_stream(current_user)

And in the view we can render it like twitter as:

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

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

Tags: , ,
This entry was posted on Sunday, August 1st, 2010 at 7:48 am and is filed under rubyonrails, twitter. 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