Ruby progress bar
mouse 1961 · person cloud · link
Last update
2017-09-28
2017
09-28
« — »

Enhance your iterations with a nice progressbar:

1
gem install progressbar

extend the Enumerable module:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
PROGRESSBAR_OPTIONS = {
  title:          'steps',
  starting_at:    0,
  total:          100,
  progress_mark:  '#',
  remainder_mark: '_',
  length:         79,
  format:         '%t: %J [%B] %e',
}

module Enumerable
  def create_progressbar
    ProgressBar.create PROGRESSBAR_OPTIONS.merge({
      total: (respond_to?(:length) ? self.length : 100),
    })
  end # create_progressbar -----------------------------------------------------

  def each_with_progressbar(options = {})
    pb = self.create_progressbar

    each do |blk|
      pb.increment
      yield blk
    end
  end # each_with_progressbar --------------------------------------------------
  alias :each_with_pb           :each_with_progressbar
  alias :each_with_progress_bar :each_with_progressbar

  def map_with_progressbar(options = {})
    pb = self.create_progressbar

    map do |blk|
      pb.increment
      yield blk
    end
  end # map_with_progressbar ---------------------------------------------------
  alias :map_with_pb            :map_with_progressbar
  alias :map_with_progress_bar  :map_with_progressbar
end

then use it like this:

1
2
(1..100).each_with_pb{|i| sleep 0.1 }
(1..100).map_with_pb{|i| sleep 0.1; i }

Note: If you use Rails then put that snippet in config/initializers/enumerable.rb.


Source: progressbar gem, each with progressbar gem, Stackoverflow