Commit 30299524ce73749a0bfcd05171f3a485791e5a94

Authored by Dhruv Kapadia
1 parent 08c534ca

Adding parameter to find average votes of people who have voted

app/models/question.rb
... ... @@ -204,6 +204,20 @@ class Question < ActiveRecord::Base
204 204 result.merge!(:visitor_votes => visitor.votes.count(:conditions => {:question_id => self.id}))
205 205 result.merge!(:visitor_ideas => visitor.choices.count)
206 206 end
  207 +
  208 + # this might get cpu intensive if used too often. If so, store the calculated value in redis
  209 + # and expire after X minutes
  210 + if params[:with_average_votes]
  211 + votes_by_visitors = self.votes.count(:group => 'voter_id')
  212 +
  213 + if votes_by_visitors.size > 0
  214 + average = votes_by_visitors.inject(0){|total, (k,v)| total = total + v}.to_f / votes_by_visitors.size.to_f
  215 + else
  216 + average = 0.0
  217 + end
  218 +
  219 + result.merge!(:average_votes => (average*100).round / 100.0) # round to 2 decimals
  220 + end
207 221  
208 222 return result
209 223  
... ...
spec/models/question_spec.rb
... ... @@ -170,6 +170,22 @@ describe Question do
170 170 @question_optional_information[:future_appearance_id_1].should_not == future_appearance_id_1
171 171 end
172 172  
  173 + it "should provide average voter information" do
  174 + params = {:id => 124, :visitor_identifier => "jim", :with_prompt => true, :with_appearance => true, :with_average_votes => true }
  175 + @question_optional_information = @question.get_optional_information(params)
  176 + @question_optional_information[:average_votes].should be_an_instance_of(Float)
  177 + @question_optional_information[:average_votes].should be_close(0.0, 0.1)
  178 +
  179 + vote_options = {:visitor_identifier => "jim",
  180 + :appearance_lookup => @question_optional_information[:appearance_id],
  181 + :prompt => Prompt.find(@question_optional_information[:picked_prompt_id]),
  182 + :direction => "left"}
  183 +
  184 + @aoi_clone.record_vote(vote_options)
  185 + @question_optional_information = @question.get_optional_information(params)
  186 + @question_optional_information[:average_votes].should be_close(1.0, 0.1)
  187 + end
  188 +
173 189 it "should properly handle tracking the prompt cache hit rate when returning the same appearance when a visitor requests two prompts without voting" do
174 190 params = {:id => 124, :with_visitor_stats=> true, :visitor_identifier => "jim", :with_prompt => true, :with_appearance => true}
175 191 @question.clear_prompt_queue
... ...