Over a million developers have joined DZone.

Twittering Around In Ruby

DZone's Guide to

Twittering Around In Ruby

Free Resource
This code uses the Twitter4R v0.2.0 which is a complete Ruby library that provides access to all documented Twitter REST APIs (and some experimental features).

Read more at:

You will first need to install the Twitter4R Ruby Gem: sudo gem install twitter4r.

gem('twitter4r', '>=0.2.0')

login = 'mylogin' # change this
password = 'mypass' # change this
friend = 'myfriend' # change this

client = Twitter::Client.new(:login => login, :password => password)
public_timeline = client.timeline_for(:public) do |status|
  # do something here with each individual status in timeline that is also returned
  puts status.text

# can also pass a block like above to process each individual status object returned in timeline
friends_timeline = client.timeline_for(:friends) 

# same as above with block if you want
friend_timeline = client.timeline_for(:friend, friend)

# Retrieve the user object (with all public profile information) for my friend
user = Twitter::User.find(friend)

# If I don't want to be friends any more I "defriend" the user...

# Now I realize that was a terrible mistake and "befriend" them...

# At this point I want to send them a private message to let them know I made a mistake
# You can do this in two ways.
message = Twitter::Message.create(:client => client, :user => user, 
  :text => "I didn't really mean to defriend you.  Sorry!")
# OR...
message = client.message(:post, "I didn't really mean to defriend you.  Sorry!", user)

# Now I want to post a new status to my own timeline.
# This can be done one of two ways...
status = Twitter::Status.create(:client => client, :text => 'Sleeping off the beer from last night')
# OR...
status = client.status(:post, 'Sleeping off the beer from last night')

# Now I realize my mother is on twitter and wouldn't like to see me talking about beer,
# so assuming she doesn't have IM or SMS alerts we can delete the evidence....
client.status(:delete, status)

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}