Class: WebVTT::File

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(webvtt_file) ⇒ File

Returns a new instance of File.



30
31
32
33
34
35
36
37
38
39
# File 'lib/webvtt/parser.rb', line 30

def initialize(webvtt_file)
  if !::File.exists?(webvtt_file)
    raise InputError, "WebVTT file not found"
  end

  @path = webvtt_file
  @filename = ::File.basename(@path)
  @content = ::File.read(webvtt_file).gsub("\r\n", "\n") # normalizing new line character
  parse
end

Instance Attribute Details

#cuesObject

Returns the value of attribute cues.



28
29
30
# File 'lib/webvtt/parser.rb', line 28

def cues
  @cues
end

#filenameObject (readonly)

Returns the value of attribute filename.



27
28
29
# File 'lib/webvtt/parser.rb', line 27

def filename
  @filename
end

#headerObject (readonly)

Returns the value of attribute header.



27
28
29
# File 'lib/webvtt/parser.rb', line 27

def header
  @header
end

#pathObject (readonly)

Returns the value of attribute path.



27
28
29
# File 'lib/webvtt/parser.rb', line 27

def path
  @path
end

Instance Method Details

#actual_total_lengthObject



49
50
51
# File 'lib/webvtt/parser.rb', line 49

def actual_total_length
  @cues.last.end_in_sec - @cues.first.start_in_sec
end

#parseObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/webvtt/parser.rb', line 62

def parse
  # remove bom first
  @content.gsub!("\uFEFF", '')

  cues = @content.split("\n\n")
  @header = cues.shift
  header_lines = @header.split("\n").map(&:strip)
  if (header_lines[0] =~ /^WEBVTT/).nil?
    raise MalformedFile, "Not a valid WebVTT file"
  end

  @cues = []
  cues.each do |cue|
    cue_parsed = Cue.parse(cue.strip)
    if !cue_parsed.text.nil?
      @cues << cue_parsed
    end
  end
  @cues
end

#save(output = nil) ⇒ Object



53
54
55
56
57
58
59
60
# File 'lib/webvtt/parser.rb', line 53

def save(output=nil)
  output ||= @path.gsub(".srt", ".vtt")

  ::File.open(output, "w") do |f|
    f.write(to_webvtt)
  end
  return output
end

#to_webvttObject



41
42
43
# File 'lib/webvtt/parser.rb', line 41

def to_webvtt
  [@header, @cues.map(&:to_webvtt)].flatten.join("\n\n")
end

#total_lengthObject



45
46
47
# File 'lib/webvtt/parser.rb', line 45

def total_length
  @cues.last.end_in_sec
end