Class: AwsCftTools::ThreadedOutput

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/aws_cft_tools/threaded_output.rb

Overview

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.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(real_stdout) ⇒ ThreadedOutput

Returns a new instance of ThreadedOutput.

Parameters:

  • real_stdout (IO)

    The file object that should be written to with prefixed text.



17
18
19
20
21
# 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

Class Method Details

.prefixObject

The prefix for output from the current thread.



29
30
31
# File 'lib/aws_cft_tools/threaded_output.rb', line 29

def self.prefix
  Thread.current['output_prefix'] || ''
end

.prefix=(prefix) ⇒ Object

Parameters:

  • prefix (String)

    The prefix for each line of text output by the calling thread.



36
37
38
# File 'lib/aws_cft_tools/threaded_output.rb', line 36

def self.prefix=(prefix)
  Thread.current['output_prefix'] = prefix + ': '
end

Instance Method Details

#flushObject

Ensure all buffered text is output. If any text is output, a newline is output as well.



43
44
45
46
# 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.

Parameters:

  • args (Array<String>)


71
72
73
74
75
76
# 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

#puts(*args) ⇒ Object

Writes all of the arguments to the output with prefixes. Appends a newline to each argument.

Parameters:

  • args (Array<String>)


61
62
63
# File 'lib/aws_cft_tools/threaded_output.rb', line 61

def puts(*args)
  print(args.join("\n") + "\n")
end

#write(string) ⇒ Object

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.



52
53
54
# File 'lib/aws_cft_tools/threaded_output.rb', line 52

def write(string)
  print(string)
end