In a little app that I recently launched I tried to use Twitters API. Turns out it’s incredible easy to do so if you use Ruby on Rails.
Here are the things that I needed to do to get a first version running:
Create a new Rails application. Then create a Model Twitter that extends Rails’ ActiveResource:
class Twitter < ActiveResource::Base self.site = "http://twitter.com" self.user = "yourusername" self.password = "yourpassword" self.element_name = "status" end
As you can see you can add the credentials to your Twitter account. Because Twitter’s API uses <status> as root element of the API’s XML we set “elmenet_name” to status.
Well that’s all you have to do. Fire up the console (ruby script/console) type in
Twitter.post(:update, :status => "Yay, I just used the API")
and you will see you just twittered with rails.
Other operations are simple to. If you – for example – want to load all replies to your account just use:
Twitter.get(:replies)
.
Additional goody:
If you want to use an URL-shortener within ruby you can use the API of is.gd:
url = Net::HTTP.get 'is.gd', '/api.php?longurl=' + CGI.escape("http://somereallylongurl.com/blub") Twitter.post(:update, :status => "Here: " + url)
