My Life As A Blog

Ruby Tuesday #17 : Ain’t no party like an HTTParty

leave a comment »

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 ''
  format :xml

  def download_public_timeline

  def download_friends_timeline(username, password)
    download_timeline("statuses/friends_timeline/#{username}.xml", username, password)

  def download_user_timeline(username)

  def update(update_text, username, password)"update.xml", { :query => {:status => update_text}, :basic_auth => {:username => username, :password => password}})

  def download_timeline(path, username=nil, password=nil)
    self.class.get(path, {:basic_auth => {:username => username, :password => password}}

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 = 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.


Written by remark

August 5, 2008 at 7:30 am

Posted in Development, Ruby

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: