1. Computing
Send to a Friend via Email

How to Use the Twitter Gem for Ruby

Twittering With Ruby

By

Using the Twitter Gem

John Nunemaker has wrapped all the Twitter goodness of Ruby into a Gem called (aptly enough) twitter. Using this gem, making API requests to Twitter is even easier than using the twitter method. Perhaps more importantly, the Twitter gem also parses the output for you, and gives you a very easy interface to the data.

Installing the Twitter gem is the same as installing any other gem. It doesn't need any native extensions, so you can use it anywhere.

 $ sudo gem install twitter
 

If we re-write our previous follow example, it comes out to just 20 lines including whitespace!

 #!/usr/bin/env ruby
 require 'rubygems'
 require 'twitter'
 
 twitter = Twitter::Base.new( 'aboutruby', 'pass123' )
 
 last_id = 1
 while true
   timeline = twitter.timeline( :friends, :since_id => last_id )
 
   unless timeline.empty?
     last_id = timeline[0].id
 
     timeline.reverse.each do|st|
       puts "#{st.user.name} said #{st.text}"
     end
 
     sleep 300
   end
 end
 

The first step is to create the twitter object. Simply construct a Twitter::Base object and give it your username and password. No surprises there.

To request a timeline, such as the friends timeline, call the timeline method. If given no options, it will request the friends timeline. However, since we want to use the since_id option, we'll have to add the :friends parameter and the :since_id hash parameter. The rest of the code is straightforward. Note how easy it is to get information from the status updates. For example, to get the ID of the latest update, just do timeline[0].id!

Even simpler is the previous example that posts a new update. This progam is all of two meaningful lines.

 #!/usr/bin/env ruby
 require 'rubygems'
 require 'twitter'
 
 twitter = Twitter::Base.new( 'aboutruby', 'pass123' )
 
 twitter.update ARGV[0]
 

For more information about the twitter gem, see its homepage and documentation.

See More About

©2014 About.com. All rights reserved.