Class: TrickBag::Io::TextModeStatusUpdater
- Inherits:
-
Object
- Object
- TrickBag::Io::TextModeStatusUpdater
- Defined in:
- lib/trick_bag/io/text_mode_status_updater.rb
Overview
Updates the terminal line with text, erasing the original content and displaying at the same place. Uses ANSI escape sequences for cursor positioning and clearing (see www.oldlinux.org/Linux.old/Ref-docs/ASCII/ANSI%20Escape%20Sequences.htm).
Example:
updater = TrickBag::Io::TextModeStatusUpdater.new(->{ Time.now }) 5.times { updater.print; sleep(1) }
Instance Method Summary collapse
-
#initialize(text_generator, outstream = $stdout, force_output_non_tty = false) ⇒ TextModeStatusUpdater
constructor
A new instance of TextModeStatusUpdater.
-
#print(*args) ⇒ Object
Causes the text generator lambda to be called, calls to_s on its result, and outputs the resulting text to the output stream, moving the cursor left to the beginning of the previous call’s output if not the first call to print.
Constructor Details
#initialize(text_generator, outstream = $stdout, force_output_non_tty = false) ⇒ TextModeStatusUpdater
Returns a new instance of TextModeStatusUpdater.
15 16 17 18 19 20 |
# File 'lib/trick_bag/io/text_mode_status_updater.rb', line 15 def initialize(text_generator, outstream = $stdout, force_output_non_tty = false) @text_generator = text_generator @outstream = outstream @force_output_non_tty = force_output_non_tty @first_time = true end |
Instance Method Details
#print(*args) ⇒ Object
Causes the text generator lambda to be called, calls to_s on its result, and outputs the resulting text to the output stream, moving the cursor left to the beginning of the previous call’s output if not the first call to print.
Since this method uses ASCII escape sequences that would look messy in a file, this method will silently return if the output stream is not a TTY, unless
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/trick_bag/io/text_mode_status_updater.rb', line 32 def print(*args) # If output is being redirected, don't print anything; it will look like garbage; # But if output was forced (e.g. to write to a string), then allow it. return unless @outstream.tty? || @force_output_non_tty if @first_time @first_time = false else @outstream.print(move_cursor_left_text(@prev_text_length)) end text = @text_generator.(*args).to_s @prev_text_length = text.length @outstream.print(clear_to_end_of_line_text + text) end |