Jan 21, 2012

Quick Tip: Using the Progress Bar gem

I've got a long running rake task.  Yep, I hate to have it but it's necessary.  So rather than just sit back and wonder how long it's going to take and how long I've already been waiting, I decided to take a look at the progress_bar gem.  Using it is fairly simple.. you can take a look at the documentation for some nifty options but let me step you through a very simple example on how I use it in a rake task.



require 'progress_bar'

desc "Do some awesome thing that takes a long time"
task :my_rake_task => :environment do |t|

  progress_bar = ProgressBar.new(Person.count)

  Person.all.each do |person|
    progress_bar.increment!
    person.gender = person.gender.downcase
    person.save
  end

end

Super simple. Here we have a few key things to remember:


  1.    1. Require the progress_bar gem and make sure it's in your Gemfile

  2.    2. Set up a new progress bar outside your loop and set the max correctly. In our case we're doing something for each Person so we'll set the total amount of records to the count of everybody in our Person model.

  3.    3. Increment the progress bar in the loop. By default you increment by 1 but read the docs if that's not what you want.


And that's it! I first ran into this gem from using the sunspot:reindex rake task. It's perfect for something like that and adds a little polish to your work.

No comments:

Post a Comment