Class: HumanSeconds

Inherits:
Object
  • Object
show all
Defined in:
lib/human_seconds.rb,
lib/human_seconds/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(total_seconds) ⇒ HumanSeconds

Returns a new instance of HumanSeconds.



6
7
8
# File 'lib/human_seconds.rb', line 6

def initialize(total_seconds)
  @total_seconds = total_seconds
end

Instance Attribute Details

#total_secondsObject (readonly)

Returns the value of attribute total_seconds.



4
5
6
# File 'lib/human_seconds.rb', line 4

def total_seconds
  @total_seconds
end

Class Method Details

.parse(str) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# 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

Instance Method Details

#to_iObject



23
24
25
# File 'lib/human_seconds.rb', line 23

def to_i
  total_seconds
end

#to_sObject



27
28
29
30
31
32
33
34
# 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