1
0

vote_validator.rb 881 B

12345678910111213141516171819202122232425
  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. vote.errors.add(:base, I18n.t('polls.errors.self_vote')) if self_vote?(vote)
  7. if vote.poll.multiple? && vote.poll.votes.where(account: vote.account, choice: vote.choice).exists?
  8. vote.errors.add(:base, I18n.t('polls.errors.already_voted'))
  9. elsif !vote.poll.multiple? && vote.poll.votes.where(account: vote.account).exists?
  10. vote.errors.add(:base, I18n.t('polls.errors.already_voted'))
  11. end
  12. end
  13. private
  14. def invalid_choice?(vote)
  15. vote.choice.negative? || vote.choice >= vote.poll.options.size
  16. end
  17. def self_vote?(vote)
  18. vote.account_id == vote.poll.account_id
  19. end
  20. end