Extract methods in poll status component

This way we remove duplication in the HTML.

We're also adding a test checking what happens when users can vote in
order to test the `render?` method we've added.
This commit is contained in:
Javi Martín
2024-04-22 03:28:33 +02:00
parent b2a49cd291
commit 1b9d321c4e
3 changed files with 39 additions and 19 deletions

View File

@@ -1,19 +1,3 @@
<% if current_user %>
<% if current_user.unverified? %>
<div class="access-status unverified" title="<%= t("polls.index.unverified") %>">
<span class="show-for-sr"><%= t("polls.index.unverified") %></span>
</div>
<% elsif cannot?(:answer, poll) %>
<div class="access-status cant-answer" title="<%= t("polls.index.cant_answer") %>">
<span class="show-for-sr"><%= t("polls.index.cant_answer") %></span>
</div>
<% elsif !poll.votable_by?(current_user) %>
<div class="access-status already-answer" title="<%= t("polls.index.already_answer") %>">
<span class="show-for-sr"><%= t("polls.index.already_answer") %></span>
</div>
<% end %>
<% else %>
<div class="access-status not-logged-in" title="<%= t("polls.index.not_logged_in") %>">
<span class="show-for-sr"><%= t("polls.index.not_logged_in") %></span>
</div>
<% end %>
<div class="access-status <%= html_class %>" title="<%= text %>">
<span class="show-for-sr"><%= text %></span>
</div>

View File

@@ -5,4 +5,32 @@ class Polls::AccessStatusComponent < ApplicationComponent
def initialize(poll)
@poll = poll
end
def render?
attributes.present?
end
private
def text
attributes[:text]
end
def html_class
attributes[:class]
end
def attributes
if current_user
if current_user.unverified?
{ text: t("polls.index.unverified"), class: "unverified" }
elsif cannot?(:answer, poll)
{ text: t("polls.index.cant_answer"), class: "cant-answer" }
elsif !poll.votable_by?(current_user)
{ text: t("polls.index.already_answer"), class: "already-answer" }
end
else
{ text: t("polls.index.not_logged_in"), class: "not-logged-in" }
end
end
end

View File

@@ -37,4 +37,12 @@ describe Polls::AccessStatusComponent do
expect(page).to have_css ".already-answer", count: 1
expect(page).to have_content "You already have participated in this poll"
end
it "is not rendered when users can vote" do
sign_in(create(:user, :level_two))
render_inline Polls::AccessStatusComponent.new(create(:poll))
expect(page).not_to be_rendered
end
end