class SubtitleChunk

Attributes

begin[R]
body[R]
end[R]

Public Class Methods

new(chunk) click to toggle source

Can be initialized either from a string in the SRT format, or from a hash of the begin and end timestamps and the body.

# File lib/subtitle_chunk.rb, line 17
def initialize chunk
  if chunk.is_a? Hash
    @body = chunk[:body]
    @begin = Duration.new chunk[:begin]
    @end = Duration.new chunk[:end]
  else
    chunk.match /^\d+(?<NEWLINE>\r?\n)(?<BEGIN>(?<TIME>\d{2}:\d{2}:\d{2},\d{3})) --> (?<END>\g<TIME>)\k<NEWLINE>(?<BODY>.+)$/m do |match|
      @body = match['BODY']
      @begin = duration match['BEGIN']
      @end = duration match['END']
    end or raise ParseError.new "Invalid subtitle chunk: #{chunk}"
  end

  @body.strip!
  raise EmptyBodyError.new "Body cannot be empty." if @body.empty?
  raise OverlapError.new "Duration cannot be negative." if @begin.to_f > @end.to_f
end

Public Instance Methods

+(seconds) click to toggle source
# File lib/subtitle_chunk.rb, line 50
def + seconds
  SubtitleChunk.new body: @body,
               begin: @begin + seconds,
               end: @end + seconds
end
-(seconds) click to toggle source
# File lib/subtitle_chunk.rb, line 56
def - seconds
  self + (-seconds)
end
initialize_copy(source) click to toggle source
Calls superclass method
# File lib/subtitle_chunk.rb, line 35
def initialize_copy source
  super
  @begin, @end = @begin.dup, @end.dup
end
shift(seconds) click to toggle source
# File lib/subtitle_chunk.rb, line 46
def shift seconds
  self + seconds
end
shift!(seconds) click to toggle source
# File lib/subtitle_chunk.rb, line 40
def shift! seconds
  shifted = self + seconds
  @begin, @end = shifted.begin, shifted.end
  self
end
to_s(order = nil) click to toggle source
# File lib/subtitle_chunk.rb, line 60
  def to_s order = nil
    output = ""
    output << "#{order}\n" unless order.nil?
    output << <<-EOS
#{@begin} --> #{@end}
#{@body}
    EOS
  end

Protected Instance Methods

duration(stamp) click to toggle source

Parse the SRT timestamp format HH:MM:SS,SSS into Duration.

# File lib/subtitle_chunk.rb, line 71
def duration stamp
  stamp.match /(?<HOURS>\d{2}):(?<MINUTES>\d{2}):(?<SECONDS>\d{2}),(?<MILLISECONDS>\d{3})/ do |match|
    hours = match['HOURS'].to_f
    minutes = hours * 60 + match['MINUTES'].to_f
    seconds = minutes * 60 + "#{match['SECONDS']}.#{match['MILLISECONDS']}".to_f
    Duration.new seconds
  end or raise ArgumentError.new "Invalid duration stamp: #{stamp}"
end