The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

22 lines
727 B

  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