Last active
October 3, 2019 19:44
-
-
Save olly/3941982 to your computer and use it in GitHub Desktop.
Progress Bars for Ruby's CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More detailed explanation: http://51degrees.net/2012/10/23/progress-bars-for-ruby-csv.html