From: James Gray Date: 2008-01-04T07:45:37+09:00 Subject: Re: Way of handling CLI interface for chat program. On Jan 3, 2008, at 3:53 PM, Michael wrote: > Consider the following example: > --------------------------------------------------- > th = Thread.new { loop do puts "Hello, Ruby!"; sleep(10) end } > while (line = Readline.readline("prompt> ", true)) > puts "#{line}: processed" > end > --------------------------------------------------- > > This code will produce such results: > --------------------------------------------------- > $ ./cli.rb > Hello, Ruby! > prompt> I WAS TYPING HERE FOR 10 SECONDSHello, Ruby! > --------------------------------------------------- > And what I want, it's ALL lines be put above my input prompt, and not > interrupting me while I'm typing. This doesn't clear the lines as you were asking for, but hopefully it will give you new ideas: #!/usr/bin/env ruby -wKU require "thread" require "timeout" require "rubygems" require "highline/system_extensions" incoming_messages = Queue.new output_buffer = String.new # simulate incoming server messages Thread.new do loop do incoming_messages << "AnnoyingUser: Hi, I'm still here!" sleep 5 end end # main event loop prompt = true loop do # handle output unless incoming_messages.empty? puts unless prompt puts incoming_messages.shift until incoming_messages.empty? prompt = true end puts incoming_messages.shift until incoming_messages.empty? # prompt if prompt print ">> #{output_buffer}" $stdout.flush prompt = false end # fetch input begin Timeout.timeout(0.1) do if char = HighLine::SystemExtensions.get_character.chr output_buffer << char print char $stdout.flush end end rescue Timeout::Error # do nothing -- we'll try again later end # handle full lines of input if output_buffer[-1, 1] == "\n" incoming_messages << "Sending '#{output_buffer.chomp}' to server..." output_buffer = String.new prompt = true end end __END__ James Edward Gray II