X-Git-Url: https://projects.mako.cc/source/rubyvote/blobdiff_plain/0ef8f53fb812bcc40337a92f9c4d11ab193f73a9..c9649b477b0e94c4f7f36e6d42225e0d6a113f57:/lib/rubyvote/election.rb diff --git a/lib/rubyvote/election.rb b/lib/rubyvote/election.rb index 7fd8396..1d98d91 100644 --- a/lib/rubyvote/election.rb +++ b/lib/rubyvote/election.rb @@ -42,7 +42,11 @@ class ElectionVote if votes if votes.instance_of?( Array ) votes.each do |vote| - self.tally_vote(vote) if self.verify_vote(vote) + if self.verify_vote(vote) + self.tally_vote(vote) + else + raise InvalidVoteError.new("Invalid vote object", vote) + end end else raise ElectionError, "Votes must be in the form of an array.", caller @@ -58,9 +62,10 @@ class ElectionVote end # by default, this does nothing. it must be redefined in any subclass - def tally_vote + def tally_vote(vote) self.verify_vote(vote) end + end class PluralityVote < ElectionVote @@ -70,7 +75,7 @@ class PluralityVote < ElectionVote protected def verify_vote(vote=nil) - vote.instance_of?( String ) + vote ? true : false end def tally_vote(candidate) @@ -103,12 +108,18 @@ end ## Election Result Classes ## -## There classes are used to compute and report the results of an -## election. In almost all cases, these will be returned by the -## #results method of a corresponding ElectionVote subclass. - +# ElectionResult and its subclasses are used to identify and report the results +# of an election. In almost all cases, these will be returned by the #results +# method of a corresponding ElectionVote subclass. +# +# Each ElectionResult object has the following methods: +# +# * #winner? -- return Boolean as to the winner or winners of an election +# * #winners -- an array of winners of the election +# * #ranked_candidates -- (where available) a list of ranked candidates class ElectionResult attr_reader :winners + attr_reader :election def initialize(voteobj=nil) unless voteobj and voteobj.kind_of?( ElectionVote ) @@ -124,14 +135,15 @@ class ElectionResult end def winner? - @winners.length > 0 + @winners.length > 0 and not @winners[0].nil? end - + end class PluralityResult < ElectionResult attr_reader :ranked_candidates - + attr_reader :points + def initialize(voteobj=nil) super(voteobj) @@ -142,6 +154,8 @@ class PluralityResult < ElectionResult b[1] <=> a[1] end.collect {|a| a[0]} + @points = @election.votes + # winners are anyone who has the same number of votes as the # first person @winners = @ranked_candidates.find_all do |i| @@ -158,3 +172,10 @@ end class ElectionError < ArgumentError end +class InvalidVoteError < ElectionError + attr_accessor :voteobj + def initialize(msg=nil, voteobj=nil) + super(msg) + @voteobj=voteobj + end +end