Class: Sxn::UI::ProgressBar

Inherits:
Object
  • Object
show all
Defined in:
lib/sxn/ui/progress_bar.rb

Overview

Progress bars for long-running operations

Defined Under Namespace

Classes: Stepper

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(title, total: 100, format: :classic) ⇒ ProgressBar

Returns a new instance of ProgressBar.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/sxn/ui/progress_bar.rb', line 9

def initialize(title, total: 100, format: :classic)
  format_string = case format
                  when :classic
                    "#{title} [:bar] :percent :elapsed"
                  when :detailed
                    "#{title} [:bar] :current/:total (:percent) :elapsed ETA: :eta"
                  when :simple
                    "#{title} :percent"
                  else
                    title
                  end

  @bar = TTY::ProgressBar.new(format_string, total: total, clear: true)
end

Class Method Details

.for_operation(title, total_steps: 5, &block) ⇒ Object



64
65
66
67
68
69
70
71
72
# File 'lib/sxn/ui/progress_bar.rb', line 64

def self.for_operation(title, total_steps: 5, &block)
  progress = new(title, total: total_steps, format: :detailed)

  stepper = Stepper.new(progress)
  result = block.call(stepper)

  progress.finish
  result
end

.with_progress(title, items, format: :classic, &block) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/sxn/ui/progress_bar.rb', line 48

def self.with_progress(title, items, format: :classic, &block)
  return [] if items.empty?

  progress = new(title, total: items.size, format: format)
  results = []

  items.each do |item|
    result = block.call(item, progress)
    results << result
    progress.advance
  end

  progress.finish
  results
end

Instance Method Details

#advance(step = 1) ⇒ Object



24
25
26
# File 'lib/sxn/ui/progress_bar.rb', line 24

def advance(step = 1)
  @bar.advance(step)
end

#currentObject



32
33
34
# File 'lib/sxn/ui/progress_bar.rb', line 32

def current
  @bar.current
end

#finishObject



28
29
30
# File 'lib/sxn/ui/progress_bar.rb', line 28

def finish
  @bar.finish
end

#log(message) ⇒ Object



44
45
46
# File 'lib/sxn/ui/progress_bar.rb', line 44

def log(message)
  @bar.log(message)
end

#percentObject



40
41
42
# File 'lib/sxn/ui/progress_bar.rb', line 40

def percent
  @bar.percent
end

#totalObject



36
37
38
# File 'lib/sxn/ui/progress_bar.rb', line 36

def total
  @bar.total
end