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.



174
175
176
177
178
179
180
181
182
# File 'lib/webvtt/parser.rb', line 174

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



159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/webvtt/parser.rb', line 159

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



195
196
197
# File 'lib/webvtt/parser.rb', line 195

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

#to_fObject



191
192
193
# File 'lib/webvtt/parser.rb', line 191

def to_f
  @timestamp.to_f
end

#to_sObject



184
185
186
187
188
189
# File 'lib/webvtt/parser.rb', line 184

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