Ruby Tuesday #17 : Ain’t no party like an HTTParty
This week, I noticed on RubyInside that there’s a new gem called HTTParty that simplifies calling APIs over HTTP. Since this is exactly what I have been doing with Twitter and SSDS I thought I’d have a look at it. First port of call is the example on RubyForge. There’s some more examples on github – the Twitter example is here.
The next step is to take the Twitter client I wrote before and refactor it to use HTTParty. Here’s the resulting code:
require 'httparty' class Twitter include HTTParty base_uri 'twitter.com' formatml def download_public_timeline download_timeline('statuses/public_timeline.xml') end def download_friends_timeline(username, password) download_timeline("statuses/friends_timeline/#{username}.xml", username, password) end def download_user_timeline(username) download_timeline("statuses/user_timeline/#{username}.xml") end def update(update_text, username, password) self.class.post("update.xml", { :query => {:status => update_text}, :basic_auth => {:username => username, :password => password}}) end private def download_timeline(path, username=nil, password=nil) self.class.get(path, {:basic_auth => {:username => username, :password => password}} end end
Add a little code to call the class to make sure it works:
require "Twitter" require 'pp' $KCODE = "u" username = 'Put your username here'
password= 'Put your password here' client = Twitter.new puts "Public Timeline\r\n" puts "***********************" pp client.download_public_timeline puts "***********************" puts "Friends Timeline\r\n" puts "***********************" pp client.download_friends_timeline(username, password) puts "***********************" puts "User Timeline\r\n" puts "***********************" pp client.download_user_timeline(username) puts "***********************" client.update("Tweeting with Ruby via HTTParty", username, password)
And it all works – apart from a few of the usual timeouts and grumbles from Twitter. Less code and simpler code. This time around I’m using pp (pretty-printer) to format the output – this gives a good view of what HTTParty is returning. My next step with HTTParty is to use it for the SSDS code I wrote.