/
eta.rb
53 lines (43 loc) · 1.07 KB
/
eta.rb
1
2
3
4
5
6
7
8
9
10
11
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
47
48
49
50
51
52
53
# frozen_string_literal: true
require 'progress/elapsed_time'
class Progress
# Estimate time of arrival
class Eta
def initialize
@started_at = ElapsedTime.now
end
def left(completed)
seconds = seconds_left(completed)
return unless seconds && seconds > 0
seconds_to_string(seconds)
end
def elapsed
seconds_to_string(ElapsedTime.now - @started_at)
end
private
def seconds_to_string(seconds)
return unless seconds
case seconds
when 0...60
format '%.0fs', seconds
when 60...3600
format '%.1fm', seconds / 60
when 3600...86_400
format '%.1fh', seconds / 3600
else
format '%.1fd', seconds / 86_400
end
end
def seconds_left(completed)
now = ElapsedTime.now
return unless completed > 0 && now - @started_at >= 1
current_eta = @started_at + (now - @started_at) / completed
@left = if @left
@left + (current_eta - @left) * (1 + completed) * 0.5
else
current_eta
end
@left - now
end
end
end