Posted by tom January 30th, 2007
I’ve recently discovered Twitter and made a small Ruby class for it, to be further extended into the full API. I’ve included the sourcecode in this post, but …
I found out somebody already wrote a whole gem with the complete api, which you can install using
sudo gem install twitterHere’s the code anyway:
require 'net/http'
class Twitter
attr_accessor :username
attr_accessor :password
TIMELINE_FRIENDS = 1
TIMELINE_PUBLIC = 2
def initialize( username = "", password = "" )
@username = username
@password = password
end
def update( status = "" )
req = Net::HTTP::Post.new('/statuses/update.xml')
req.basic_auth( @username, @password )
req.set_form_data({'status'=>status}, ';')
res = Net::HTTP.new('twitter.com', 80).start do |http|
http.request(req)
end
res.body
end
def timeline(timeline = TIMELINE_FRIENDS )
if timeline == TIMELINE_FRIENDS
path = '/statuses/friends_timeline.xml'
else
path = '/statuses/public_timeline.xml'
end
req = Net::HTTP::Get.new(path)
req.basic_auth( @username, @password )
res = Net::HTTP.new('twitter.com', 80).start do |http|
http.request(req)
end
res.body
end
end
# Change here ...
t = Twitter.new("<your-email>","<your-password>")
puts t.timeline
You can use the update method to post a new update like so:
t = Twitter.new("<your-email>","<your-password>")
puts t.update("Checking out this nice class Tom made")
Oh, and while you’re at it: add me to your friends list …

Leave a Reply