Class: CountedEach::Counter

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

Instance Method Summary collapse

Constructor Details

#initialize(list) ⇒ Counter

Returns a new instance of Counter.



11
12
13
14
# File 'lib/counted_each.rb', line 11

def initialize(list)
  @list = list
  @t_start = nil
end

Instance Method Details

#elapsedObject



37
38
39
# File 'lib/counted_each.rb', line 37

def elapsed
  Time.now - @t_start
end

#iterate(with_index, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/counted_each.rb', line 16

def iterate(with_index, &block)
  @total = @list.count
  start
  @list.each_with_index do |item, pos|
    @current = pos
    with_index ? block.call(item, pos) : block.call(item)
    Config.output.print "   %i/%i Elapsed: %s   Time to Complete: %s       \r" % [pos+1, @total, time_format(elapsed), time_format(to_go)]
    Config.output.flush
  end
  stop
  Config.output.puts
end

#startObject



29
30
31
# File 'lib/counted_each.rb', line 29

def start
  @t_start = Time.now
end

#stopObject



33
34
35
# File 'lib/counted_each.rb', line 33

def stop
  @t_stop = Time.now
end

#time_format(seconds) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/counted_each.rb', line 45

def time_format(seconds)
  return '00:00' if seconds.infinite?
  h = (seconds/3600).floor
  m = ((seconds - (h*3600))/60).floor
  s = (seconds - (m * 60) - (h*3600)).floor
  
  "%d:%02d:%02d" % [h, m, s]
end

#to_goObject



41
42
43
# File 'lib/counted_each.rb', line 41

def to_go
  (elapsed / @current) * (@total - @current)
end