-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathapp.rb
33 lines (29 loc) · 975 Bytes
/
app.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
STREAMING_URL = 'http://stream.twitter.com/1/statuses/sample.json'
TWITTER_USERNAME = ENV['TWITTER_USERNAME']
TWITTER_PASSWORD = ENV['TWITTER_PASSWORD']
configure do
if ENV['MONGOHQ_URL']
uri = URI.parse(ENV['MONGOHQ_URL'])
conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'])
DB = conn.db(uri.path.gsub(/^\//, ''))
else
DB = Mongo::Connection.new.db("mongo-twitter-streaming")
end
DB.create_collection("tweets", :capped => true, :size => 10485760)
end
get '/' do
content_type 'text/html', :charset => 'utf-8'
@tweets = DB['tweets'].find({}, :limit => 10, :sort => [[ '$natural', :desc ]])
erb :index
end
EM.schedule do
http = EM::HttpRequest.new(STREAMING_URL).get :head => { 'Authorization' => [ TWITTER_USERNAME, TWITTER_PASSWORD ] }
buffer = ""
http.stream do |chunk|
buffer += chunk
while line = buffer.slice!(/.+\r?\n/)
tweet = JSON.parse(line)
DB['tweets'].insert(tweet) if tweet['text']
end
end
end