Class: Webvtt::File

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_file) ⇒ File

Returns a new instance of File.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/webvtt/file.rb', line 7

def initialize(input_file)
  if input_file.is_a?(String)
    input_file = input_file.encode('UTF-8')
    if ::File.exist?(input_file)
      @file = ::File.read(input_file)
    else
      @file = input_file
    end
  elsif input_file.is_a?(::File)
    @file = input_file.read
  else
    raise
  end
  @cues = []
  @header_lines = []
  parse
end

Instance Attribute Details

#cuesObject

Returns the value of attribute cues.



5
6
7
# File 'lib/webvtt/file.rb', line 5

def cues
  @cues
end

#fileObject

Returns the value of attribute file.



5
6
7
# File 'lib/webvtt/file.rb', line 5

def file
  @file
end

#header_linesObject

Returns the value of attribute header_lines.



5
6
7
# File 'lib/webvtt/file.rb', line 5

def header_lines
  @header_lines
end

Instance Method Details

#parseObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/webvtt/file.rb', line 25

def parse
  remove_bom
  if !webvtt_line?(file.lines.first)
    raise Webvtt::MalformedError
  end
  in_header = true
  collected_lines = []
  file_lines = file.dup.lines.to_a

  file_lines.each_with_index do |line,index|
    line.chomp!

    if webvtt_line?(line)
      next
    end
    if line.empty?
      # If the line is empty then we can't be in the header anymore.
      if in_header
        in_header = false
      else
        if !collected_lines.empty? and !notes?(collected_lines)
          add_a_cue(collected_lines)
        end
        collected_lines = []
      end
    elsif !line.empty? and file_lines.length == (index + 1) # add our last cue
      collected_lines << line
      add_a_cue(collected_lines)
    elsif in_header
      header_lines << line
    else
      collected_lines << line
    end
  end
end

#remove_bomObject



65
66
67
# File 'lib/webvtt/file.rb', line 65

def remove_bom
  file.gsub!("\uFEFF", '')
end

#webvtt_line?(line) ⇒ Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/webvtt/file.rb', line 61

def webvtt_line?(line)
  line[0,6] == 'WEBVTT'
end