Class: MovingWords::SrtParser

Inherits:
Object
  • Object
show all
Defined in:
lib/moving_words/srt_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ SrtParser

Public: Sets up a new parser based on the given data.



7
8
9
# File 'lib/moving_words/srt_parser.rb', line 7

def initialize(data)
  self.data = data
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



3
4
5
# File 'lib/moving_words/srt_parser.rb', line 3

def data
  @data
end

Instance Method Details

#parseObject

Public: Converts the caption data to a set of ‘CaptionBlock` objects.

Returns an array of ‘CaptionBlock`s



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/moving_words/srt_parser.rb', line 15

def parse
  blocks = []
  block_content = ""
  data.each_line do |line|
    if line.strip.empty?
      blocks << parse_caption_block(block_content) unless block_content.empty?
      block_content = ""
    else
      block_content += line
    end
  end

  # Handle any final content
  blocks << parse_caption_block(block_content) unless block_content.empty?

  blocks
end

#parse_caption_block(block_content) ⇒ Object

Internal: Converts a caption block in the SRT data to a ‘CaptionBlock` object.

block_content - The text for the content block

to parse.

Returns a ‘CaptionBlock`



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/moving_words/srt_parser.rb', line 40

def parse_caption_block(block_content)
  lines = block_content.split("\n")

  time_line = lines[1]
  times = time_line.split("-->")
  times = times.map { |t| t.strip }

  start_time = subrip_time_to_ms(times[0])
  end_time = subrip_time_to_ms(times[1])
  content = lines[2..-1].join("\n")

  CaptionBlock.new(start_time, end_time, content)
end

#subrip_time_to_ms(subrip_time) ⇒ Object

Internal: Converts a subrip time code to milliseconds

subrip_time - The subrip time string



57
58
59
60
61
62
# File 'lib/moving_words/srt_parser.rb', line 57

def subrip_time_to_ms(subrip_time)
  seconds, millis = subrip_time.split(",")
  hours, minutes, seconds = seconds.split(":")

  millis.to_i + (seconds.to_i * 1000) + (minutes.to_i * 60000) + (hours.to_i * 3600000)
end