Class: WebVTT::Timestamp

Inherits:
Object
  • Object
show all
Defined in:
lib/webvtt/parser.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(time) ⇒ Timestamp

Returns a new instance of Timestamp.



201
202
203
204
205
206
207
208
209
# File 'lib/webvtt/parser.rb', line 201

def initialize( time )
  if time.is_a? Numeric
    @timestamp = time
  elsif time.is_a? String
    @timestamp = Timestamp.parse_seconds( time )
  else
    raise ArgumentError.new("time not numeric nor a string")
  end
end

Class Method Details

.parse_seconds(timestamp) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/webvtt/parser.rb', line 186

def self.parse_seconds( timestamp )
  if mres = timestamp.match(/\A([0-9]{2}):([0-9]{2}):([0-9]{2}\.[0-9]{3})\z/)
    sec = mres[3].to_f # seconds and subseconds
    sec += mres[2].to_f * 60 # minutes
    sec += mres[1].to_f * 60 * 60 # hours
  elsif mres = timestamp.match(/\A([0-9]{2}):([0-9]{2}\.[0-9]{3})\z/)
    sec = mres[2].to_f # seconds and subseconds
    sec += mres[1].to_f * 60 # minutes
  else
    raise ArgumentError.new("Invalid WebVTT timestamp format: #{timestamp.inspect}")
  end

  return sec
end

Instance Method Details

#+(other) ⇒ Object



222
223
224
# File 'lib/webvtt/parser.rb', line 222

def +(other)
  Timestamp.new self.to_f + other.to_f
end

#to_fObject



218
219
220
# File 'lib/webvtt/parser.rb', line 218

def to_f
  @timestamp.to_f
end

#to_sObject



211
212
213
214
215
216
# File 'lib/webvtt/parser.rb', line 211

def to_s
  hms = [60,60].reduce( [ @timestamp ] ) { |m,o| m.unshift(m.shift.divmod(o)).flatten }
  hms << (@timestamp.divmod(1).last * 1000).round

  sprintf("%02d:%02d:%02d.%03d", *hms)
end