Class: TriviaParser

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

Instance Method Summary collapse

Constructor Details

#initialize(file, debug = false) ⇒ TriviaParser

Returns a new instance of TriviaParser.



4
5
6
7
# File 'lib/trivia_parser.rb', line 4

def initialize(file, debug = false)
  @file = file
  @debug = debug
end

Instance Method Details

#parseObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
# File 'lib/trivia_parser.rb', line 9

def parse
  @doc = Kramdown::Document.new(@file)
  state = :not_found
  questions = []
  question = {}
  @doc.root.children.each do |c|
    p [state, c.type] if @debug

    if state == :trivia_started && c.type == :header && c.options[:level] == 2
      state = :not_found
    end

    if c.type == :header && c.options[:level] == 2 && c.options[:raw_text] == "Trivia"
      state = :trivia_started
      question = {}
    end

    if state == :answer_parsing && c.type == :ul
      answers = []
      c.children.map do |li|
        head = li.children.first.children.first
        if head.type == :strong
          answers.push({
            text: head.children.first.value,
            isAnswer: true
          })
        else
          answers.push({
            text: head.value
          })
        end
      end

      question[:answers] = answers
      state = :trivia_started
    end

    if state == :trivia_started && c.type == :blockquote 
      questions.push(question) unless question.empty?
      question = {
        question: c.children.first.children.first.value
      }
      state = :answer_parsing
    end
  end
  questions.push(question) unless question.empty?
  questions
end