Motivation: SD News is a "social news site" (basically a Hacker News clone), written in Rails, that I work on as part of my efforts with a Christian publishing company I run with some friends.  As part of the administrative backend, I wanted to be able to send posts to our Twitter profile.  The site is still young, and the community still growing, so I wanted the admins to have complete control over what gets sent to Twitter.  I had thought of automating this process based on which items have the most votes in a given time period, but trust is easy to lose and all it would take is 1 or 2 irrelevant, or irreverent. posts to lose that trust.

Methodology: I would first need a good Twitter gem for Ruby, and I'd need to decide which URL shortening service I'd use.  Ruby Twitter seemed to be the simplest gem for Twitter.  For the URL shortening I chose bit.ly, because the bitly gem seemed like the easiest, and the documentation was good.  My plan of attack was:

  1. Grab one item from the queue, that has not been Twittered
  2. Shorten the URL via bitly
  3. Send the item's title and shortened URL to Twitter
  4. Save the shortened URL in the database so I could retrieve stats later

The script that did this would be run every hour.

Implementation:
The two gems made this an almost trivial implementation.

require 'twitter'
require 'bitly'

@item = Item.find(:first, :conditions => "send_to_twitter = 1 and twitterd = 0", :order => "posted_on desc")

if !@item.nil?
   b = Bitly.new(username, password)
   @url = b.shorten("http://news.sensusdivinitatis.com/item/#{@item.id}").short_url

   httpauth = Twitter::HTTPAuth.new(username, password)
   base = Twitter::Base.new(httpauth)
   base.update("#{@item.title[0...110]} - #{@url}") #shorten the title if it's too long

   Item.update(@item.id, :twitterd => 1, :bitly_url => @url) #save the bit.ly url
end

That's pretty much it.  Incidentally, the bitly gem makes it very easy to grab the stats for any URL.  For instance, if you wanted to see how many clicks a given URL has received:

require 'twitter'
require 'bitly'

@item = Item.find(id)
b = Bitly.new(username, password)
@clicks = b.stats(i.bitly_url).stats["clicks"]

Done.

No related posts.