vote_validator.rb 727 B

123456789101112131415161718192021
  1. # frozen_string_literal: true
  2. class VoteValidator < ActiveModel::Validator
  3. def validate(vote)
  4. vote.errors.add(:base, I18n.t('polls.errors.expired')) if vote.poll.expired?
  5. vote.errors.add(:base, I18n.t('polls.errors.invalid_choice')) if invalid_choice?(vote)
  6. if vote.poll.multiple? && vote.poll.votes.where(account: vote.account, choice: vote.choice).exists?
  7. vote.errors.add(:base, I18n.t('polls.errors.already_voted'))
  8. elsif !vote.poll.multiple? && vote.poll.votes.where(account: vote.account).exists?
  9. vote.errors.add(:base, I18n.t('polls.errors.already_voted'))
  10. end
  11. end
  12. private
  13. def invalid_choice?(vote)
  14. vote.choice.negative? || vote.choice >= vote.poll.options.size
  15. end
  16. end