Each with progress bar and benchmark

January 15th, 2016 - Bonn

Time to time we have to run operations on the console just for developing purposes that are applied to a set of elements and which take minutes or more to finish. To have an idea of how long these operations take and when they will be over, we added the tqdm gem https://github.com/powerpak/tqdm-ruby

Now we can call .tqdm on enumerables to get something like this (example from their repo):

You could do an expensive operation on every user like this

User.all.tqdm.each do |user|
  #(...)
end

If that operation involves more queries, you might want to turn off logging

ActiveRecord::Base.logger.silence do
  User.all.tqdm.each do |user|
    #(...)
  end
end

We also benchmark often these operations

Benchmark.measure do
  ActiveRecord::Base.logger.silence do
    # ...
  end
end

If you do this quite often you might want to extend Enumerable like this:

module Enumerable
  def measure(&block)
    Benchmark.measure do
      ActiveRecord::Base.logger.silence do
        self.tqdm.each(&block)
      end
    end
  end
end