13 January 2010

Displaying status feed of twitter in Rails

Couple of days ago I needed to show twitter status in a rails application. The specification was to show the last 5 status of a twitter account. Twitter itself has a good API. But I used twitter gem which left me to do just a couple of lines of code.

Twitter gem supports both OAuth and HTTP Auth. I used HTTP Auth for authentication. Let me dig in to code.

First of all, install twitter gem.

gem install twitter
Load ruby gem to environment.rb.
require 'twitter'

Then perform the authentication using HTTP Auth. You need to provide your user id and password of the twitter account. You should read this from a config file. For the simplicity I am placing it at code.

def twitter_feed   
httpauth = Twitter::HTTPAuth.new(‘twitter_account_name’, ‘twitter_account_password’)    
twitter_client = Twitter::Base.new(httpauth)
@latest_status_feeds = twitter_client.user_timeline[0..4] if twitter_client.present?
#it will show most recent 5 status. If you would like to show recent 20 don't put any bar.
render :partial=>"twitter_feed"   

In twitter_feed partial you can display the text using some properties.

<h4>Latest Tweet</h4>   
<%if @latest_status_feeds.present?%>    
  <%  @latest_status_feeds.each do | @latest_status_feed|%>    
    <p>"<%= @latest_status_feed.text %>"<br /><span class="time" style="font-size:11px;font-style:italic;">
<%= convert_date(@latest_status_feed.created_at.to_date) %></span></p>    

This will show the last 5 status from your twitter feed.

If you would like to show the twitter feeds of your friends, the following tweak is needed to be made:

    @friends_feeds =     twitter_client.friends_timeline 

You can display from the view in the same way!

That's it! Pretty simple, yeah? Happy coding.