Last Updated: February 24, 2019
·
3.679K
· nick-desteffen

Rake Progress Bar

It's nice to see progress when running rake tasks over a bunch of records. This is a little class that I use, it updates the screen with the progress of the job.

 class ProgressBar

  def initialize(total)
    @total   = total
    @counter = 1
  end

  def increment
    complete = sprintf("%#.2f%", ((@counter.to_f / @total.to_f) * 100))
    print "\r\e[0K#{@counter}/#{@total} (#{complete})"
    @counter += 1
  end

end

To use it in your rake task:

task :foo_bar do
  items = (1..1000).to_a
  progress_bar = ProgressBar.new(items.size)
  items.each do |item|
    item.to_s ## Call a real method here, example: `item.update(foo: 'bar')`
    progress_bar.increment
  end
end

1 Response
Add your response

This was useful to me in a project just now! I made one small change, adding a parameter to be used as a descriptive string:

class ProgressBar

  def initialize(total, description)
    @description  = description
    @total  = total
    @counter = 1
  end

  def increment
    complete = sprintf("%#.2f%", ((@counter.to_f / @total.to_f) * 100))
    print "\r\e[0K#{@description} #{@counter}/#{@total} (#{complete})"
    @counter += 1
  end

end
over 1 year ago ·