galbator1x

Untitled

Dec 23rd, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.31 KB | None | 0 0
  1. class AnswerQuestion
  2.   include Interactor
  3.  
  4.   def call
  5.     if not game
  6.       context.fail!(message: 'Game is not started', code: 403)
  7.     elsif question_in_round_session?
  8.       context.fail!(message: 'Question answered', code: 403)
  9.     else
  10.       questions << question
  11.       if update_game_attributes
  12.         context.right = answer_right?
  13.         context.comment = question.comment
  14.         context.answers = question.answers
  15.       else
  16.         context.fail!(message: game.errors, code: 422)
  17.       end
  18.     end
  19.   end
  20.  
  21.   private
  22.  
  23.   def question_in_round_session?
  24.     questions.include?(question)
  25.   end
  26.  
  27.   def answer_right?
  28.     answers.sort == question.answers.sort
  29.   end
  30.  
  31.   def update_game_attributes
  32.     if answer_right?
  33.       game.increment!(:right_answers)
  34.     else
  35.       game.increment!(:wrong_answers)
  36.     end
  37.  
  38.     game.increment!(:questions_number)
  39.     game.score += question.category.cost
  40.  
  41.     game.save
  42.   end
  43.  
  44.   def game
  45.     @game ||= context.user.games.where(ended_at: nil).first
  46.   end
  47.  
  48.   def answers
  49.     _answers = context.answers
  50.     @answers ||= if _answers.is_a?(String) then JSON.parse _answers else _answers end
  51.   end
  52.  
  53.   def questions
  54.     @questions ||= game.round_sessions.last.questions
  55.   end
  56.  
  57.   def question
  58.     @question ||= Question.find(context.question_id)
  59.   end
  60. end
Add Comment
Please, Sign In to add comment