Class: Prefab::Duration

Inherits:
Object
  • Object
show all
Defined in:
lib/prefab/duration.rb

Constant Summary collapse

PATTERN =
/P(?:(?<days>\d+(?:\.\d+)?)D)?(?:T(?:(?<hours>\d+(?:\.\d+)?)H)?(?:(?<minutes>\d+(?:\.\d+)?)M)?(?:(?<seconds>\d+(?:\.\d+)?)S)?)?/
MINUTES_IN_SECONDS =
60
HOURS_IN_SECONDS =
60 * MINUTES_IN_SECONDS
DAYS_IN_SECONDS =
24 * HOURS_IN_SECONDS

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(definition) ⇒ Duration

Returns a new instance of Duration.



10
11
12
# File 'lib/prefab/duration.rb', line 10

def initialize(definition)
  @seconds = self.class.parse(definition)
end

Class Method Details

.parse(definition) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/prefab/duration.rb', line 14

def self.parse(definition)
  match = PATTERN.match(definition)
  return 0 unless match

  days = match[:days]&.to_f || 0
  hours = match[:hours]&.to_f || 0
  minutes = match[:minutes]&.to_f || 0
  seconds = match[:seconds]&.to_f || 0

  (days * DAYS_IN_SECONDS + hours * HOURS_IN_SECONDS + minutes * MINUTES_IN_SECONDS + seconds)
end

Instance Method Details

#as_jsonObject



54
55
56
# File 'lib/prefab/duration.rb', line 54

def as_json
  { ms:  in_seconds * 1000, seconds: in_seconds }
end

#in_daysObject



38
39
40
# File 'lib/prefab/duration.rb', line 38

def in_days
  in_hours / 24.0
end

#in_hoursObject



34
35
36
# File 'lib/prefab/duration.rb', line 34

def in_hours
  in_minutes / 60.0
end

#in_minutesObject



30
31
32
# File 'lib/prefab/duration.rb', line 30

def in_minutes
  in_seconds / 60.0
end

#in_secondsObject



26
27
28
# File 'lib/prefab/duration.rb', line 26

def in_seconds
  @seconds
end

#in_weeksObject



42
43
44
# File 'lib/prefab/duration.rb', line 42

def in_weeks
  in_days / 7.0
end

#to_fObject



50
51
52
# File 'lib/prefab/duration.rb', line 50

def to_f
  in_seconds.to_f
end

#to_iObject



46
47
48
# File 'lib/prefab/duration.rb', line 46

def to_i
  in_seconds.to_i
end