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 = Twitter::HTTPAuth.new(user.twitter_username, user.twitter_password)
      client = Twitter::Base.new(httpauth)
      timelines = client.friends_timeline
      return nil unless timelines.is_a?(Array)
      streams = []
      timelines.each do |timeline|
        stream = Stream.new
        stream.message = timeline.text
        stream.id = timeline.id.to_s+"_twitter"
        stream.time = timeline.created_at
        stream.name = (timeline.user.screen_name rescue nil)
        # if timeline.user.profile_image_url is nil, you can add your application's custom default image
        stream.photo = (timeline.user.profile_image_url rescue nil)
        stream.user = stream.name ? User.find_by_twitter(stream.name) : nil
        streams << stream
      end
      streams
    rescue
      return nil
    end

  end

end

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>
   <div style="float:left;">
     <%= image_tag stream.photo %>
   </div>

   <div style="float:left" class='stream_messag'>
     <span class="name"><%= stream.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>
   </div>
  </div>
<%  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