Displaying status feed of twitter in Rails

January 12, 2010

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.

[sourcecode language=”ruby”] gem install twitter
[/sourcecode] Load ruby gem to environment.rb.
[sourcecode language=”ruby”] require ‘twitter’
[/sourcecode] 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.
[sourcecode language=”ruby”] 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”
[/sourcecode] In twitter_feed partial you can display the text using some properties.

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

[/sourcecode] 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:

[sourcecode language=”ruby”] @friends_feeds = twitter_client.friends_timeline
[/sourcecode] You can display from the view in the same way!

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

Contributor: Fuad Bin Omar, COO, Nascenia

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.