Skip to content

Instantly share code, notes, and snippets.

@carrfane
Created July 26, 2019 03:02
Show Gist options
  • Save carrfane/1170a94cdc0b5a3756cddf2a3f792d6f to your computer and use it in GitHub Desktop.
Save carrfane/1170a94cdc0b5a3756cddf2a3f792d6f to your computer and use it in GitHub Desktop.
class QuestionSerializer < ActiveModel::Serializer
attributes :id,
:content,
:type,
:answers_count,
:answer_size
def answers_count
return self.send(object.type) if %w[binary_swipe prioritise_top3 select_many date_picker].include?(object.type)
return uniq_answers if %w[freeform_text audio picture].include?(object.type)
filtered_answers.group(:content).count
end
def answer_size
filtered_answers.count
end
def prioritise_top3
answers = filtered_answers.map { |answer| answer.content[0] }
answers.uniq.map { |answer| { "#{answer}": answers.count(answer) } }.reduce({}, :merge)
end
def select_many
answers = filtered_answers.map(&:content).flatten
answers.uniq.map { |answer| { "#{answer}": answers.count(answer) } }.reduce({}, :merge)
end
def date_picker
answers = filtered_answers.map(&:content).flatten
answers.uniq.map { |answer| { "#{answer.to_date}": answers.count(answer) } }.reduce({}, :merge)
end
def binary_swipe
answers = filtered_answers.map(&:content).flatten
answers.uniq.map { |answer| {
"#{answer}": {
"positive": answers.flatten.count(answer),
"negative": answer_size - answers.flatten.count(answer)
} }
}.reduce({}, :merge)
end
def filtered_answers
story_id = instance_options[:story_id]
object.answers.where(story_id: story_id)
end
def uniq_answers
filtered_answers.map{ |answer| { content: answer.content } }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment