Skip to content

Instantly share code, notes, and snippets.

@kenn
Created March 20, 2010 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kenn/338337 to your computer and use it in GitHub Desktop.
Save kenn/338337 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'sinatra'
require 'em-http'
require 'json'
get '/tweets' do
content_type 'text/html', :charset => 'utf-8'
TWEETS.map {|tweet| "<p><b>#{tweet['user']['screen_name']}</b>: #{tweet['text']}</p>" }.join
end
class RingBuffer < Array
def initialize(size)
@max = size
super(0)
end
def push(object)
shift if size == @max
super
end
end
TWEETS = RingBuffer.new(10)
STREAMING_URL = 'http://stream.twitter.com/1/statuses/sample.json'
def handle_tweet(tweet)
return unless tweet['text']
TWEETS.push(tweet)
end
EM.schedule do
http = EM::HttpRequest.new(STREAMING_URL).get :head => { 'Authorization' => [ 'USERNAME', 'PASSWORD' ] }
buffer = ""
http.stream do |chunk|
buffer += chunk
while line = buffer.slice!(/.+\r?\n/)
handle_tweet JSON.parse(line)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment