Skip to content

Commit

Permalink
Merge pull request #3678 from consul/fix_nan_score
Browse files Browse the repository at this point in the history
Fix Infinity exceptions in hot score calculator
  • Loading branch information
javierm committed Sep 10, 2019
2 parents e25d0eb + 53abc57 commit 48b1287
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/score_calculator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@ module ScoreCalculator
def self.hot_score(resource)
return 0 unless resource.created_at

period = [
Setting["hot_score_period_in_days"].to_i,
((Time.current - resource.created_at) / 1.day).ceil
].min
period = [1, [max_period, resource_age(resource)].min].max

votes_total = resource.votes_for.where("created_at >= ?", period.days.ago).count
votes_up = resource.get_upvotes.where("created_at >= ?", period.days.ago).count
Expand All @@ -27,4 +24,12 @@ def self.confidence_score(votes_total, votes_up)
score * (votes_up / votes_total) * 100
end

def self.max_period
Setting["hot_score_period_in_days"].to_i
end

def self.resource_age(resource)
((Time.current - resource.created_at) / 1.day).ceil
end

end
29 changes: 29 additions & 0 deletions spec/lib/score_calculator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
require "rails_helper"

describe ScoreCalculator do
describe ".hot_score" do
let(:resource) { create(:debate) }

before do
resource.vote_by(voter: create(:user), vote: "yes")
end

it "ignores small time leaps", :with_frozen_time do
resource.created_at = Time.current + 0.01

expect(ScoreCalculator.hot_score(resource)).to eq 1
end

it "ignores setting with negative value " do
Setting["hot_score_period_in_days"] = -1

expect(ScoreCalculator.hot_score(resource)).to eq 1
end

it "ignores setting with zero value" do
Setting["hot_score_period_in_days"] = 0

expect(ScoreCalculator.hot_score(resource)).to eq 1
end
end
end

0 comments on commit 48b1287

Please sign in to comment.