Class: CourseExam::Grader

Inherits:
Object
  • Object
show all
Defined in:
app/services/course_exam/grader.rb

Overview

Service object: grades a CourseExam attempt.

Marks every answered exam question (CustomerTopic) completed, sums the
TopicResponse#score points of the learner's selected answers, persists the
total on the exam, and fires the pass/fail state-machine event. The pass
transition side-effects (learner email, internal notification, completing
the enrollment) live on CourseExam's state machine and are triggered here
exactly once: grading is idempotent — an exam that already passed or failed
is reported as-is without re-transitioning or re-sending emails.

Scoring is an absolute-points comparison: the summed score must reach
#cutoff_mark (the exam definition's +min_score_to_pass+).

Defined Under Namespace

Classes: Result

Instance Method Summary collapse

Constructor Details

#initialize(course_exam) ⇒ Grader

Returns a new instance of Grader.

Parameters:

  • course_exam (CourseExam)

    the attempt to grade



26
27
28
# File 'app/services/course_exam/grader.rb', line 26

def initialize(course_exam)
  @course_exam = course_exam
end

Instance Method Details

#callResult

Grades the exam and fires the pass/fail transition.

Returns:

  • (Result)

    the outcome; +already_graded?+ is true when the exam had
    already passed or failed and nothing was changed

Raises:

  • (ArgumentError)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/services/course_exam/grader.rb', line 34

def call
  raise ArgumentError, 'course_exam is required' if course_exam.nil?

  return already_graded_result if course_exam.passed? || course_exam.failed?

  score = compute_and_persist_score
  # The transition (and its emails/enrollment completion) stays outside the
  # scoring transaction so a mailer hiccup can't roll back the score.
  #
  # Lock and reload to guard against concurrent graders racing to transition
  # the same exam. If another grader won, return their result.
  course_exam.with_lock do
    course_exam.reload
    if course_exam.passed? || course_exam.failed?
      return already_graded_result
    end
    # Still in_progress under lock; safe to transition now
    score >= course_exam.cutoff_mark ? course_exam.pass : course_exam.fail
  end

  Result.new(score: score, cutoff: course_exam.cutoff_mark, passed: course_exam.passed?)
end