ijr6jq
Last Updated: February 25, 2016
·
2.064K
· nick-desteffen
Img 2817

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
Say Thanks
Respond

2 Responses
Add your response

13826
Cartoony brian

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 ·
26277
Rsz img 20141114 190753090

Hi Nick DeSteffen , Thanks for the post, i am getting the following error when i try to initialize the class from rake task

ArgumentError: wrong number of arguments (1 for 0)

Full error message available in stackoverflow

http://stackoverflow.com/questions/34959479/ruby-class-argumenterror-wrong-number-of-arguments-1-for-0

over 1 year ago ·