Sha256: 64d202d40fc3fcf21e50f9628ae26c7b14b140201e16f8be77124dd0832b139e

Contents?: true

Size: 1.42 KB

Versions: 15

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

module Decidim
  module Surveys
    # This command is executed when the user answers a Survey.
    class AnswerSurvey < Rectify::Command
      # Initializes a AnswerSurvey Command.
      #
      # form - The form from which to get the data.
      # survey - The current instance of the survey to be answered.
      def initialize(form, current_user, survey)
        @form = form
        @current_user = current_user
        @survey = survey
      end

      # Answers a survey if it is valid
      #
      # Broadcasts :ok if successful, :invalid otherwise.
      def call
        return broadcast(:invalid) if @form.invalid?

        answer_survey
        broadcast(:ok)
      end

      private

      def answer_survey
        SurveyAnswer.transaction do
          @form.survey_answers.each do |form_answer|
            answer = SurveyAnswer.new(
              user: @current_user,
              survey: @survey,
              question: form_answer.question,
              body: form_answer.body
            )

            form_answer.selected_choices.each do |choice|
              answer.choices.build(
                body: choice.body,
                custom_body: choice.custom_body,
                decidim_survey_answer_option_id: choice.answer_option_id,
                position: choice.position
              )
            end

            answer.save!
          end
        end
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
decidim-surveys-0.15.2 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.15.1 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.15.0 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.14.4 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.14.3 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.14.2 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.14.1 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.13.1 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.12.2 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.13.0 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.12.1 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.13.0.pre1 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.12.0 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.11.2 app/commands/decidim/surveys/answer_survey.rb
decidim-surveys-0.12.0.pre app/commands/decidim/surveys/answer_survey.rb