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_feedhttpauth = 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”
end[/sourcecode] In twitter_feed partial you can display the text using some properties. [sourcecode language=”ruby”]
Latest Tweet
“”
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
More to Explore
The Quest for Knowledge Continues. Fuel Your Curiosity.

