Class: Batch

Inherits:
Object
  • Object
show all
Defined in:
lib/batch.rb

Constant Summary collapse

VERSION =
"0.0.3"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enumerable) ⇒ Batch

Returns a new instance of Batch.



6
7
8
9
10
# File 'lib/batch.rb', line 6

def initialize(enumerable)
  @enumerable = enumerable
  @width = (ENV["BATCH_WIDTH"] || 75).to_i
  @size = enumerable.size if enumerable.respond_to?(:size)
end

Instance Attribute Details

#enumerableObject (readonly)

Returns the value of attribute enumerable.



4
5
6
# File 'lib/batch.rb', line 4

def enumerable
  @enumerable
end

Class Method Details

.each(enumerable, &block) ⇒ Object



84
85
86
# File 'lib/batch.rb', line 84

def self.each(enumerable, &block)
  new(enumerable).each(&block)
end

.start(title, enumerable, &block) ⇒ Object



88
89
90
91
92
93
# File 'lib/batch.rb', line 88

def self.start(title, enumerable, &block)
  puts
  puts(title)
  puts
  each(enumerable, &block)
end

Instance Method Details

#each(&block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/batch.rb', line 12

def each(&block)
  @errors = []
  @current = 0

  report_progress

  enumerable.each do |item|
    begin
      yield(item)
      print "."

    rescue Interrupt => e
      raise e

    rescue Exception => e
      print "E"
      @errors << [item, e]

    ensure
      @current += 1

      if eol?
        print "\n"
        report_progress
      end
    end
  end

  print "\n"
  puts "100% " unless eol?

  report_errors

  nil
end

#eol?Boolean

Returns:

  • (Boolean)


80
81
82
# File 'lib/batch.rb', line 80

def eol?
  @current % @width == 0
end

#progressObject



66
67
68
69
70
# File 'lib/batch.rb', line 66

def progress
  return unless @size

  @current * 100 / @size
end

#report_error(item, error) ⇒ Object



58
59
60
# File 'lib/batch.rb', line 58

def report_error(item, error)
  $stderr.puts "#{item.inspect}: #{error}\n"
end

#report_errorsObject



48
49
50
51
52
53
54
55
56
# File 'lib/batch.rb', line 48

def report_errors
  return if @errors.empty?

  $stderr.puts "\nSome errors occured:\n\n"

  @errors.each do |item, error|
    report_error(item, error)
  end
end

#report_progressObject



72
73
74
75
76
77
78
# File 'lib/batch.rb', line 72

def report_progress
  if progress
    print "#{progress.to_s.rjust 3, " "}% "
  else
    print "   ? "
  end
end

#totalObject



62
63
64
# File 'lib/batch.rb', line 62

def total
  @size
end