Class: Rubikon::ProgressBar

Inherits:
Object show all
Defined in:
lib/rubikon/progress_bar.rb

Overview

A class for displaying and managing progress bars

See Also:

Author:

  • Sebastian Staudt

Since:

  • 0.2.0

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ ProgressBar

Create a new ProgressBar using the given options.

Parameters:

  • options (Hash, Numeric) (defaults to: {})

    A Hash of options to customize the progress bar or the maximum value of the progress bar

Options Hash (options):

  • :char (String) — default: '#'

    The character used for progress bar display

  • :maximum (Numeric) — default: 100

    The maximum value of this progress bar

  • :ostream (IO) — default: $stdout

    The output stream where the progress bar should be displayed

  • :size (Numeric) — default: 20

    The actual size of the progress bar

  • :start (Numeric) — default: 0

    The start value of the progress bar

See Also:

  • Application::InstanceMethods#progress_bar

Since:

  • 0.2.0



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rubikon/progress_bar.rb', line 30

def initialize(options = {})
  if options.is_a? Numeric
    @maximum = options
    options = {}
  else
    @maximum = options[:maximum] || 100
  end
  @maximum.round

  @progress_char  = options[:char] || '#'
  @ostream        = options[:ostream] || $stdout
  @progress       = 0
  @size           = options[:size] || 20
  @factor         = @size.round.to_f / @maximum
  @value          = 0
  @brackets       = options[:brackets] || false
  @bracket_filler = options[:bracket_filler] || ' '

  if @brackets
    @ostream << '[' + @bracket_filler * @size + ']'+ "\b" * (@size + 1)
    @ostream.flush
  end
  self + (options[:start] || 0)
end

Instance Method Details

#+(value = 1) ⇒ ProgressBar

Add an amount to the current value of the progress bar

This triggers a refresh of the progress bar, if the added value actually changes the displayed bar.

Examples:

Different alternatives to increase the progress

progress_bar + 1 # (will add 1)
progress_bar + 5 # (will add 5)
progress_bar.+   # (will add 1)

Parameters:

  • value (Numeric) (defaults to: 1)

    The amount to add to the progress bar

Returns:

Since:

  • 0.2.0



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/rubikon/progress_bar.rb', line 67

def +(value = 1)
  return if (value <= 0) || (@value == @maximum)
  @value += value
  old_progress = @progress
  add_progress = ((@value - @progress / @factor) * @factor).round
  @progress += add_progress

  if @progress > @size
    @progress = @size
    add_progress = @size - old_progress
  end

  if add_progress > 0
    @ostream << @progress_char * add_progress
    @ostream.flush
    @ostream.putc 10 if @progress == @size
  end

  self
end