Class: ActiveSupport::NumberHelper::NumberToPeriodFormatConverter

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

Instance Method Summary collapse

Instance Method Details

#convertObject



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, # 1.year
    'm' => 2_592_000, # 1.month
    'd' => 86_400, # 1.day
    'H' => 3600, # 1.hour
    'M' => 60 # 1.minute
  }
  %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