class AwsCftTools::ThreadedOutput
Provides a way to process output and prefix with a thread identifier. The object is shared by threads. Each thread should set its own prefix.
Public Class Methods
@param real_stdout [IO] The file object that should be written to with prefixed text.
# File lib/aws_cft_tools/threaded_output.rb, line 17 def initialize(real_stdout) @stdout = real_stdout @buffer = Hash.new { |hash, key| hash[key] = '' } @semaphore = Mutex.new end
The prefix for output from the current thread.
# File lib/aws_cft_tools/threaded_output.rb, line 29 def self.prefix Thread.current['output_prefix'] || '' end
@param prefix [String] The prefix for each line of text output by the calling thread.
# File lib/aws_cft_tools/threaded_output.rb, line 36 def self.prefix=(prefix) Thread.current['output_prefix'] = prefix + ': ' end
Public Instance Methods
Ensure all buffered text is output. If any text is output, a newline is output as well.
# File lib/aws_cft_tools/threaded_output.rb, line 43 def flush guarded { @stdout.puts prefix + buffer } if buffer != '' self.buffer = '' end
Writes all of the arugments to the output without newlines. Will output the prefix after each newline.
@param args [Array<String>]
# File lib/aws_cft_tools/threaded_output.rb, line 71 def print(*args) append(args.join('')) printable_lines.each do |line| guarded { @stdout.puts prefix + line } end end
Writes all of the arguments to the output with prefixes. Appends a newline to each argument.
@param args [Array<String>]
# File lib/aws_cft_tools/threaded_output.rb, line 61 def puts(*args) print(args.join("\n") + "\n") end
Write the string to the output with prefixes as appropriate. If the string does not end in a newline, then the remaining text will be buffered until a newline is seen.
# File lib/aws_cft_tools/threaded_output.rb, line 52 def write(string) print(string) end
Private Instance Methods
# File lib/aws_cft_tools/threaded_output.rb, line 95 def append(value) @buffer[prefix] += value end
# File lib/aws_cft_tools/threaded_output.rb, line 91 def buffer @buffer[prefix] end
# File lib/aws_cft_tools/threaded_output.rb, line 99 def buffer=(string) @buffer[prefix] = string end
# File lib/aws_cft_tools/threaded_output.rb, line 80 def printable_lines lines = buffer.split(/\n/) if buffer[-1..-1] == "\n" self.buffer = '' else self.buffer = lines.last lines = lines[0..-2] end lines end