Class: Decidim::Surveys::DataSerializer

Inherits:
Exporters::Serializer show all
Defined in:
decidim-surveys/app/serializers/decidim/surveys/data_serializer.rb

Overview

This class serializes the specific data in each Survey. This is `Questionnaire->questions->answer_options` but not `answers` and `answer_choices`.

Instance Attribute Summary

Attributes inherited from Exporters::Serializer

#resource

Instance Method Summary collapse

Methods inherited from Exporters::Serializer

#event_name, #finalize, #initialize, #run

Constructor Details

This class inherits a constructor from Decidim::Exporters::Serializer

Instance Method Details

#serializeObject

Returns: Array of Decidim::Forms::Questionnaire as a json hash,

or nil if none exists.

11
12
13
14
15
16
17
18
19
20
# File 'decidim-surveys/app/serializers/decidim/surveys/data_serializer.rb', line 11

def serialize
  component = resource
  surveys = Decidim::Surveys::Survey.where(component: component)
  surveys.collect do |survey|
    next if survey.questionnaire.nil?

    json = serialize_survey(survey)
    json.with_indifferent_access.merge(survey_id: survey.id)
  end
end

#serialize_answer_options(answer_options) ⇒ Object


39
40
41
42
43
# File 'decidim-surveys/app/serializers/decidim/surveys/data_serializer.rb', line 39

def serialize_answer_options(answer_options)
  answer_options.collect do |option|
    option.attributes.as_json
  end
end

#serialize_questions(questions) ⇒ Object


31
32
33
34
35
36
37
# File 'decidim-surveys/app/serializers/decidim/surveys/data_serializer.rb', line 31

def serialize_questions(questions)
  questions.collect do |question|
    json = question.attributes.as_json
    json[:answer_options] = serialize_answer_options(question.answer_options)
    json
  end
end

#serialize_survey(survey) ⇒ Object


22
23
24
25
26
27
28
29
# File 'decidim-surveys/app/serializers/decidim/surveys/data_serializer.rb', line 22

def serialize_survey(survey)
  questionnaire = survey.questionnaire
  questionnaire_json = questionnaire.attributes.as_json
  questionnaire_json[:questions] = serialize_questions(questionnaire.questions.order(:position))
  json = survey.attributes.as_json
  json[:questionnaire] = questionnaire_json
  json
end