Skip to content

Commit

Permalink
API: return own vote state in polls
Browse files Browse the repository at this point in the history
  • Loading branch information
jhass committed Feb 2, 2020
1 parent b921b71 commit 8cae234
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 10 deletions.
21 changes: 12 additions & 9 deletions 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

Expand All @@ -23,10 +24,12 @@ def answers_collection_as_api_json(answers_collection)
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
3 changes: 2 additions & 1 deletion lib/schemas/api_v1.json
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions spec/presenters/poll_presenter_spec.rb
Expand Up @@ -13,12 +13,20 @@
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

Expand Down

0 comments on commit 8cae234

Please sign in to comment.