Tag Archives: twitter

Fetching Local Tweets in Ruby

Tests take forever because of all the HTTPRequests

Tests take forever because of all the HTTPRequests

As planned, I wrote a little class incorporating Geocoder and twitter_search so you can search for tweets within x miles (or kilometers) of an address.Geocoder does an excellent job of parsing addresses and twitter_search is simple and efficient.

Four thumbs up

Next phase I’d like to set up a little web interface showing tweets and tweeters. There’s something funny about hitting the internet to find out what’s going on around you.

Here’s the class, as you can see there are a few overridable defaults

require 'rubygems'
require 'geocoder'
require 'twitter_search'

class Twitter_Interface

  attr_accessor :tpp, :distance
  attr_reader   :address, :geocode
  attr          :geocoder, :client 

  def initialize addr = "", dist = "2mi", pp = 15
    @client   = TwitterSearch::Client.new
    @tpp      = pp
    @distance = dist
    @geocoder = initialize_geocoder
    set_location addr

  # Could also use Yahoo API, but it requires API key.
  def initialize_geocoder geocoder = Geocoder::GeoCoderUs.new

  def format_geocode geocode = @geocode
    if is_geocode? geocode
      return "#{geocode.latitude},#{geocode.longitude},#{@distance}"

  def tweets
    @client.query :geocode => format_geocode, :tpp => @tpp

  def address_to_geocode addr = @address
    if addr == ""
      return ""
    @geocoder.geocode addr

  def is_geocode? geocode
    geocode.respond_to? "success?" and geocode.success?

  def set_location addr
    @address = addr
    @geocode = address_to_geocode @address


And here’s how you use it

t = Twitter_Interface.new "1600 pennsylvania ave nw washington dc"

#print the twitter query formatted geocode, default distance is 2 miles
puts t.format_geocode


#fetch the Twitter_Search::Tweets within 2 miles of the white house!
tweets = t.tweets

Download a .zip of the code / tests

Searching Twitter with Ruby

After seeing this a few days ago, I thought it’d be fun and easy to whip up a little script that would dump tweets from around my area. Unfortunately, it was neither. I won’t bore you with my troubles, suffice it to say GitHub has now been added to my list of gem repositories.

I haven’t gone through much of the actual api yet, but so far it looks great. I did play around with a few different wrappers before finally getting down to business with twitter_search, which is nice, and thin, and jived nicely with my goal.

So here’s the code to fetch the last 15 tweets from ( thanks geocoder! ) my area. Simple, eh?

require 'rubygems'
require 'twitter_search'

tweets = TwitterSearch::Client.new.query :geocode => "28.599630,-81.289176,2mi"

tweets.each do |t|
  puts "@#{t.from_user} - #{t.text}n"

The next step is to figure out how to look up geocodes automatically, and maybe build some sort of web interface. But not tonight.