Skip to content

Using Enumerators

Jeff Felchner edited this page Sep 15, 2017 · 8 revisions

A long-requested feature has been to add support for Enumerators. For example if you have an array with a bunch of things that you're processing, to create a bar and auto-increment it after every item is processed.

Why Wasn't Previously Implemented

The reason I've been resistant in the past is because monkey-patching core Ruby classes is not something that I'm willing to do. Even including a file which is not required by default is not acceptable to me because once it's manually required, it still steps on the toes of everyone else's libraries.

Fortunately since Ruby 2.0, we have another option. Refinements. I'm not a huge fan of these either, but that is a different story. For this particular ruby-progressbar use case however, it quashes all of my qualms that I outlined above and gives my users something that they've been asking for.

How To Use It

If you want to add Enumerator support to your project, all you have to do is include the refinement in whatever class or script you want to use it in.

Once you've done that, you can use with_progressbar on any Enumerator object.

Class Example

class MyClass
  using ProgressBar::Refinements::Enumerator

  def initialize(files = [])
    @files = files
  end

  def process
    @files.with_progressbar do |file|
      # Do process-y stuff
    end
  end
end

Script Example

#!/usr/local/bin/ruby

using ProgressBar::Refinements::Enumerator

@files = files

@files.with_progressbar do |file|
  # Do process-y stuff
end