Andrew Andrew - 4 months ago 8
Ruby Question

Running Ruby script in Terminal should 'stay awake' and not terminate once it gets to the end of the file

I have a Ruby script which I'm testing in Terminal. With this code, it doesn't immediately return, but stays awake and prints any responses:

client = TweetStream::Client.new(credentials)
client.on_direct_message do |direct_message|
puts 'direct message: ' + direct_message.text
end

client.userstream


But now, in order to test a number of these clients at once, I need to put them in their own thread, like so:

Thread.new do
client = TweetStream::Client.new(credentials)

client.on_direct_message do |direct_message|
puts 'direct message: ' + direct_message.text
end
end


The problem then is that the Ruby script returns immediately. How can I make it not immediately return, and stay awake until I do cmd+c to close it?

Answer

You can ask Ruby to wait until thread is done by using #join

t = Thread.new do
  client = TweetStream::Client.new(credentials)

  client.on_direct_message do |direct_message|
    puts 'direct message: ' + direct_message.text
  end
end

t.join