API: return own vote state in polls

This commit is contained in:
Jonne Haß 2020-02-02 14:40:02 +01:00
parent b921b71b97
commit 8cae234f45
3 changed files with 22 additions and 10 deletions

View file

@ -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

View file

@ -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

View file

@ -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