Class: TerminalProgress

Inherits:
Object
  • Object
show all
Defined in:
lib/terminal_progress.rb

Overview

Class for managing progress bars in the terminal

Instance Method Summary collapse

Constructor Details

#initialize(max) ⇒ TerminalProgress

Initialize a TermProg instance with a maximum value.

Parameters:

  • max (Integer)

    The maximum value of the progress bar.



12
13
14
15
16
17
18
19
# File 'lib/terminal_progress.rb', line 12

def initialize(max)
  Curses.raw
  instance_variable_set(:@cycle, '⣷⣯⣟⡿⢿⣻⣽⣾'.split(//).cycle)
  instance_variable_set(:@i, 0)
  instance_variable_set(:@max, max)
  instance_variable_set(:@stop, '⣾')
  instance_variable_set(:@loop, loop_thread)
end

Instance Method Details

#alive?Boolean

Check if the progress loop is still alive.

Returns:

  • (Boolean)

    Returns true if the progress loop is alive, otherwise false.



63
64
65
# File 'lib/terminal_progress.rb', line 63

def alive?
  @loop.alive?
end

#killObject

Terminate the progress loop.



56
57
58
# File 'lib/terminal_progress.rb', line 56

def kill
  Thread.kill @loop
end

#loop_threadObject



21
22
23
24
25
26
27
28
29
# File 'lib/terminal_progress.rb', line 21

def loop_thread
  Thread.new do
    loop do
      instance_variable_set(:@stop, @cycle.next)
      printf "  #{@stop}\r"
      sleep 0.0625
    end
  end
end

This is the last call to terminate the progress loop and finish rendering the bar.



50
51
52
53
# File 'lib/terminal_progress.rb', line 50

def print_complete
  printf "    #{@max}/#{@max}: [#{'='.light_yellow * width}#{suffix}\r\n"
  kill
end

Print a single line of the progress bar.



44
45
46
# File 'lib/terminal_progress.rb', line 44

def print_line
  printf "#{prefix}#{'='.light_cyan * width}#{' ' * blank}#{suffix}\r"
end

Increment the progress bar and print a message if present.

Parameters:

  • message (String, nil) (defaults to: nil)

    Optional message to display above the progress bar.



35
36
37
38
39
40
# File 'lib/terminal_progress.rb', line 35

def print_progress(message = nil)
  instance_variable_set(:@i, @max) if @i > @max
  printf "#{' ' * Curses.cols}\r#{message}\r\n" unless message.nil?
  print_line
  instance_variable_set(:@i, @i + 1)
end