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
|
# File 'lib/numeric_period_format.rb', line 19
def convert
seconds = number.to_i.abs
return seconds.to_s unless options[:format]
string = options[:format].dup
format_directives = {
'y' => 31_557_600,
'm' => 2_592_000,
'd' => 86_400,
'H' => 3600,
'M' => 60
}
%w[y m d H M].each do |item|
next unless string.match?(/%[#{item}]+/)
total = 0
value = format_directives[item]
if seconds >= value
total = seconds / value
seconds -= total * value
end
string.scan(/%[#{item}]+/).each do |match|
string.sub!(match, total.to_s.rjust(match.length - 1, '0'))
end
end
string.scan(/%[S]+/).each do |match|
string.sub!(match, seconds.to_s.rjust(match.length - 1, '0'))
end
string
end
|