Skip to content

Instantly share code, notes, and snippets.

@olly
Last active October 3, 2019 19:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olly/3941982 to your computer and use it in GitHub Desktop.
Save olly/3941982 to your computer and use it in GitHub Desktop.
Progress Bars for Ruby's CSV
require 'csv'
# https://rubygems.org/gems/progress_bar
require 'progress_bar'
class CSV
module ProgressBar
def progress_bar
::ProgressBar.new(@io.size, :bar, :percentage, :elapsed, :eta)
end
def each
progress_bar = self.progress_bar
super do |row|
yield row
progress_bar.count = self.pos
progress_bar.increment!(0)
end
end
end
class WithProgressBar < CSV
include ProgressBar
end
def self.with_progress_bar
WithProgressBar
end
end
# Usage: Module
data = File.read('data.csv')
csv = CSV.new(data)
csv.extend(CSV::ProgressBar)
csv.each do |row|
# expensive operation
end
# Usage: Subclass
CSV::WithProgressBar.foreach('data.csv') do |row|
# expensive operation
end
# Usage: Class Method
CSV.with_progress_bar.foreach('data.csv') do |row|
# expensive operation
end
@olly
Copy link
Author

olly commented Oct 23, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment