Files
danbooru/app/components/post_votes_tooltip_component.rb
evazion 8e32f656fa votes: fix division by zero in upvote ratio.
Fix a division by zero when calculating the upvote ratio in the votes tooltip.

This could happen if the post had votes according to the post_votes
table, but didn't have any votes according to the up_score and
down_score. This should never happen, yet it did happen for post 2248039
and post 2959269.
2021-11-25 23:35:09 -06:00

39 lines
897 B
Ruby

# frozen_string_literal: true
# This component represents the tooltip that displays when you hover over a post's score.
class PostVotesTooltipComponent < ApplicationComponent
attr_reader :post, :current_user
delegate :upvote_icon, :downvote_icon, to: :helpers
def initialize(post:, current_user:)
super
@post = post
@current_user = current_user
end
def votes
@post.votes.active.includes(:user).order(id: :desc)
end
def vote_icon(vote)
vote.is_positive? ? upvote_icon : downvote_icon
end
def vote_count
post.up_score + post.down_score.abs
end
def upvote_ratio
return nil if vote_count == 0
sprintf("(%.1f%%)", 100.0 * post.up_score / vote_count)
end
def voter_name(vote)
if policy(vote).can_see_voter?
link_to_user(vote.user, classes: "align-middle")
else
tag.i("hidden", class: "align-middle")
end
end
end