Module: Word2Quiz

Defined in:
lib/word_2_quiz.rb,
lib/word_2_quiz/quiz.rb,
lib/word_2_quiz/answer.rb,
lib/word_2_quiz/errors.rb,
lib/word_2_quiz/helpers.rb,
lib/word_2_quiz/version.rb,
lib/word_2_quiz/question.rb,
lib/word_2_quiz/quiz_parser.rb,
lib/word_2_quiz/quiz_solutions_parser.rb

Defined Under Namespace

Modules: Helpers Classes: Answer, InvalidAnswerKey, InvalidQuiz, Question, Quiz

Constant Summary collapse

VERSION =
"1.1.4".freeze

Class Method Summary collapse

Class Method Details

.parse_answers(file_path) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/word_2_quiz/quiz_solutions_parser.rb', line 6

def self.parse_answers(file_path)
  text = DocRipper::rip(file_path)

  if text.nil?
    raise InvalidAnswerKey.new "The uploaded answer key could not be parsed."
  end

  answers = {}

  scanner = StringScanner.new(text)

  # Quizzes accidentally uploaded as an answer key don't fail as they match
  # the regex pattern for the answer key in the questions themselves, so we
  # check that the file is actually an answer key by looking for the text that
  # shows up at the top of the columns in the answer key.

  unless text.include?("QUES ANS") && text.include?("---- ---")
    raise InvalidAnswerKey.new "The uploaded answer key is not valid."
  end

  while scanner.scan_until(/\d+\.\s+[A-Z]/)
    solution_text = scanner.matched.split(".").map(&:strip)
    answers.merge!([solution_text].to_h)
  end

  answers
end

.parse_quiz(quiz_path, answer_key_path) ⇒ Object



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

def self.parse_quiz(quiz_path, answer_key_path)
  doc = Docx::Document.open(quiz_path)
  paragraphs = doc.paragraphs
  text = doc.text

  unless Helpers.valid_quiz?(text)
    raise InvalidQuiz.new("The quiz uploaded is not a valid quiz.")
  end

  answers = Word2Quiz.parse_answers(answer_key_path)

  Quiz.from_paragraphs(paragraphs, answers)
rescue Zip::Error
  raise InvalidQuiz.new "The quiz was not a docx file."
end