Class: ClearElection::Ballot::Contest

Inherits:
Object
  • Object
show all
Defined in:
lib/clear-election-sdk/ballot.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(contestId:, choices:) ⇒ Contest

Returns a new instance of Contest.



67
68
69
70
# File 'lib/clear-election-sdk/ballot.rb', line 67

def initialize(contestId:, choices:)
  @contestId = contestId
  @choices = choices
end

Instance Attribute Details

#choicesObject (readonly)

Returns the value of attribute choices.



65
66
67
# File 'lib/clear-election-sdk/ballot.rb', line 65

def choices
  @choices
end

#contestIdObject (readonly)

Returns the value of attribute contestId.



65
66
67
# File 'lib/clear-election-sdk/ballot.rb', line 65

def contestId
  @contestId
end

Class Method Details

.from_json(data) ⇒ Object



108
109
110
111
112
113
# File 'lib/clear-election-sdk/ballot.rb', line 108

def self.from_json(data)
  self.new(
    contestId: data["contestId"],
    choices: data["choices"].each_with_index.map{|data, i| Choice.from_json(data, rank: i)}
  )
end

Instance Method Details

#<=>(other) ⇒ Object



104
105
106
# File 'lib/clear-election-sdk/ballot.rb', line 104

def <=>(other)
  self.contestId <=> other.contestId
end

#as_jsonObject



115
116
117
118
119
120
# File 'lib/clear-election-sdk/ballot.rb', line 115

def as_json
  {
    "contestId" => @contestId,
    "choices" => @choices.sort_by(&:rank).map(&:as_json)
  }
end

#validate(election) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/clear-election-sdk/ballot.rb', line 72

def validate(election)
  errors = []
  err = { contestId: contestId }
  contest = election.get_contest(contestId)
  if contest.nil?
    errors.push err.merge(message: "Invalid contest id")
  else
    if choices.length != contest.multiplicity
      errors.push err.merge(message: "Invalid multiplicity", multiplicity: choices.length)
    end
    if contest.ranked and choices.map(&:rank).sort != (0...contest.multiplicity).to_a
      errors.push err.merge(message: "Invalid ranking")
    end
    if choices.map(&:candidateId).uniq.length != choices.length
      errors.push err.merge(message: "Duplicate choices")
    end
    choices.each do |choice|
      case
      when choice.writeIn?
        if !contest.writeIn
          errors.push err.merge(message: "Write-in not allowed")
        end
      when choice.candidate?
        if !contest.candidates.map(&:candidateId).include?(choice.candidateId)
          errors.push err.merge(message: "Invalid candidate id", candidateId: choice.candidateId)
        end
      end
    end
  end
  errors
end