class HumanSeconds

Constants

VERSION

Attributes

total_seconds[R]

Public Class Methods

new(total_seconds) click to toggle source
# File lib/human_seconds.rb, line 6
def initialize(total_seconds)
  @total_seconds = total_seconds
end
parse(str) click to toggle source
# File lib/human_seconds.rb, line 10
def self.parse(str)
  m = str.match(/(\d+d)?(\d+h)?(\d+m)?(\d+s)?/)

  if m[0].empty?
    raise ArgumentError, "Unparseable string #{str}"
  else
    seconds = (m[1].to_i * 86_400) + (m[2].to_i * 3600) +
      (m[3].to_i * 60) + m[4].to_i

    new(seconds)
  end
end

Public Instance Methods

to_i() click to toggle source
# File lib/human_seconds.rb, line 23
def to_i
  total_seconds
end
to_s() click to toggle source
# File lib/human_seconds.rb, line 27
def to_s
  [
    "#{days}d",
    "#{hours}h",
    "#{minutes}m",
    "#{seconds}s",
  ].reject { |t| t.start_with?('0') }.join
end

Private Instance Methods

days() click to toggle source
# File lib/human_seconds.rb, line 42
def days
  total_seconds / 86_400
end
hours() click to toggle source
# File lib/human_seconds.rb, line 46
def hours
  ref_time.hour
end
minutes() click to toggle source
# File lib/human_seconds.rb, line 50
def minutes
  ref_time.min
end
ref_time() click to toggle source
# File lib/human_seconds.rb, line 38
def ref_time
  @ref_time ||= Time.at(0).utc + total_seconds
end
seconds() click to toggle source
# File lib/human_seconds.rb, line 54
def seconds
  ref_time.sec
end