Recently, I did an exercise using twitter streaming api to generate the most recent 10
retweets in the past n minutes.
The program is pretty simple. It sends http streaming requests to twitter api and doing sorting in the background thread, while the main thread is printing out the most recent 10 retweets.
require'twitter'require'pry'require'pp'classStreamerattr_reader:client,:background_thread,:mins,:containerdefinitialize(attributes)@client=attributes[:client]@mins=attributes[:mins]@container=attributes[:container]enddefstream@background_thread=Thread.newdo@client.sampledo|object|ifobject.is_a?(Twitter::Tweet)@container[object.created_at]||=[]@container[object.created_at]<<object.textend# Container will only keep tweets which are 5 mins up to date@container.keep_if{|time,tweet|@mins*60>Time.now-time}endendenddefstopThread.kill(@background_thread)endendclassMassagerattr_reader:raw_tweets,:top_tweets,:containerdefinitialize(attributes)@container=attributes[:container]enddeftop_tweetsbuildsortformatendprivatedefbuild@raw_tweets=Hash.new(0)@container.values.flatten.eachdo|tweet|@raw_tweets[tweet]+=1endenddefsort@raw_tweets=@raw_tweets.sort{|a,b|a[1]<=>b[1]}.last(10)enddefformat@raw_tweets.inject({})do|memo,value|memo[value[1]]||=[]memo[value[1]]<<value[0]memoendendendclassManagerattr_reader:container,:streamer,:massagerdefinitialize(attributes)@container={}@streamer=Streamer.new(container:@container,mins:attributes[:mins],client:attributes[:client])@massager=Massager.new(container:@container)endendclient=Twitter::Streaming::Client.newdo|config|config.consumer_key="#"config.consumer_secret="#"config.access_token="#"config.access_token_secret="#"endmins=1manager=Manager.new(mins:mins,client:client)manager.streamer.streamstart_time=Time.nowloopdowindow_start=Time.now-start_time>60*mins?Time.now-60*mins:start_timesleep(1)puts"------------- Top Ten Tweets from #{window_start} To #{Time.now} ---------------"ppmanager.massager.top_tweetsend