Files
old-holivud2/app/models/duration_timecode.rb

49 lines
992 B
Ruby
Raw Normal View History

2020-05-31 22:38:19 +02:00
class DurationTimecode
def self.parse(timecode)
if match = DURATION_TIMECODE_REGEX.match(timecode)
hours = match[1].to_i
minutes = match[2].to_i
seconds = match[3].to_i
new(hours, minutes, seconds)
else
raise ArgumentError.new("Must be HH:MM:SS format")
end
end
def self.from_seconds(total_seconds)
hours = total_seconds / 60 / 60
minutes = total_seconds / 60 % 60
seconds = total_seconds % 60
DurationTimecode.new(hours, minutes, seconds)
end
attr_reader :hours, :minutes, :seconds
def initialize(hours, minutes, seconds)
@hours = hours
@minutes = minutes
@seconds = seconds
end
def to_s
[hours, minutes, seconds].map { |t| t.to_s.rjust(2,'0') }.join(':')
end
def to_i
[
hours * 60 * 60,
minutes * 60,
seconds
].sum
end
def +(other)
DurationTimecode.from_seconds(to_i + other.to_i)
end
private
DURATION_TIMECODE_REGEX = /\A(\d+):(\d+):(\d+)\z/
end