diff --git a/app/presenters/poll_presenter.rb b/app/presenters/poll_presenter.rb index 84836238a..305276dae 100644 --- a/app/presenters/poll_presenter.rb +++ b/app/presenters/poll_presenter.rb @@ -1,18 +1,19 @@ # frozen_string_literal: true class PollPresenter < BasePresenter - def initialize(poll, participant_user=nil) - @poll = poll - @user = participant_user + def initialize(poll, current_user=nil) + super(poll, current_user) + + @participation = participation_answer(current_user) if current_user end def as_api_json { - guid: @poll.guid, - participation_count: @poll.participation_count, - question: @poll.question, - already_participated: @user && @poll.participation_answer(@user) ? true : false, - poll_answers: answers_collection_as_api_json(@poll.poll_answers) + guid: guid, + participation_count: participation_count, + question: question, + already_participated: @participation.present?, + poll_answers: answers_collection_as_api_json(poll_answers) } end @@ -23,10 +24,12 @@ class PollPresenter < BasePresenter end def answer_as_api_json(answer) - { + base = { id: answer.id, answer: answer.answer, vote_count: answer.vote_count } + base[:own_answer] = @participation.try(:poll_answer_id) == answer.id if current_user + base end end diff --git a/lib/schemas/api_v1.json b/lib/schemas/api_v1.json index 0f9b02ca3..1b2884bac 100644 --- a/lib/schemas/api_v1.json +++ b/lib/schemas/api_v1.json @@ -295,7 +295,8 @@ "properties": { "id": { "type": "integer" }, "answer": { "type": "string" }, - "vote_count": { "type": "integer" } + "vote_count": { "type": "integer" }, + "own_answer": { "type": "boolean" } }, "required": ["id", "answer", "vote_count"], "additionalProperties": false diff --git a/spec/presenters/poll_presenter_spec.rb b/spec/presenters/poll_presenter_spec.rb index fee0ba082..014df4362 100644 --- a/spec/presenters/poll_presenter_spec.rb +++ b/spec/presenters/poll_presenter_spec.rb @@ -13,12 +13,20 @@ describe PollPresenter do it "works with user" do presenter = PollPresenter.new(poll, alice) confirm_poll_api_json_format(presenter.as_api_json, 0, false) + expect(presenter.as_api_json[:poll_answers]).to all(include(own_answer: false)) + poll.poll_participations.create(poll_answer: poll_answer, author: alice.person) + presenter = PollPresenter.new(poll, alice) confirm_poll_api_json_format(presenter.as_api_json, 1, true) + expect(presenter.as_api_json[:poll_answers]).to include(include(id: poll_answer.id, own_answer: true)) + presenter = PollPresenter.new(poll, eve) confirm_poll_api_json_format(presenter.as_api_json, 1, false) + expect(presenter.as_api_json[:poll_answers]).to all(include(own_answer: false)) + presenter = PollPresenter.new(poll) confirm_poll_api_json_format(presenter.as_api_json, 1, false) + expect(presenter.as_api_json[:poll_answers]).to_not include(include(:own_answer)) end end