2019-03-03 21:18:23 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class VoteValidator < ActiveModel::Validator
|
|
|
|
def validate(vote)
|
|
|
|
vote.errors.add(:base, I18n.t('polls.errors.expired')) if vote.poll.expired?
|
2020-01-12 13:17:03 +00:00
|
|
|
vote.errors.add(:base, I18n.t('polls.errors.invalid_choice')) if invalid_choice?(vote)
|
2023-05-16 22:08:42 +00:00
|
|
|
vote.errors.add(:base, I18n.t('polls.errors.self_vote')) if self_vote?(vote)
|
2020-01-12 13:17:03 +00:00
|
|
|
|
2019-03-03 21:18:23 +00:00
|
|
|
if vote.poll.multiple? && vote.poll.votes.where(account: vote.account, choice: vote.choice).exists?
|
|
|
|
vote.errors.add(:base, I18n.t('polls.errors.already_voted'))
|
2019-03-03 22:41:30 +00:00
|
|
|
elsif !vote.poll.multiple? && vote.poll.votes.where(account: vote.account).exists?
|
2019-03-03 21:18:23 +00:00
|
|
|
vote.errors.add(:base, I18n.t('polls.errors.already_voted'))
|
|
|
|
end
|
|
|
|
end
|
2020-01-12 13:17:03 +00:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def invalid_choice?(vote)
|
|
|
|
vote.choice.negative? || vote.choice >= vote.poll.options.size
|
|
|
|
end
|
2023-05-16 22:08:42 +00:00
|
|
|
|
|
|
|
def self_vote?(vote)
|
|
|
|
vote.account_id == vote.poll.account_id
|
|
|
|
end
|
2019-03-03 21:18:23 +00:00
|
|
|
end
|