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.init_screen
  @cycle = '⣷⣯⣟⡿⢿⣻⣽⣾'.chars.cycle
  @i = 0
  @max = max
  @stop = '⣾'
  @loop = loop_thread
end

Instance Method Details

#add_to_max(num) ⇒ Object

Call this to dynamically add a value to the maximum value of the task bar

Raises:

  • (ArgumentError)


64
65
66
67
68
# File 'lib/terminal_progress.rb', line 64

def add_to_max(num)
  raise ArgumentError, 'num must be positive' unless num.positive?

  @max += num
end

#killObject

Terminate the progress loop.



71
72
73
74
# File 'lib/terminal_progress.rb', line 71

def kill
  Thread.kill @loop
  Curses.close_screen
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
  kill
  printf "    #{@max}/#{@max}: [#{'='.light_yellow * width}#{suffix}\r\n"
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

#update_max(new_max) ⇒ Object

Call this to dynamically update the maximum value of the task bar.

Raises:

  • (ArgumentError)


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

def update_max(new_max)
  raise ArgumentError, 'new_max must be positive' unless new_max.positive?

  @max = new_max
  @i = [@i, @max].min
end