Speedup calculated_hotness

Fix #679
This commit is contained in:
Alexander Maslov 2019-05-08 17:02:32 +03:00 committed by Peter Bhat Harkins
parent fec025f872
commit 627b6c5df7
2 changed files with 30 additions and 13 deletions

View File

@ -326,19 +326,8 @@ class Story < ApplicationRecord
base = self.tags.sum(:hotness_mod) + (self.user_is_author? && self.url.present? ? 0.25 : 0.0)
# give a story's comment votes some weight, ignoring submitter's comments
cpoints = self.merged_comments
.where("user_id <> ?", self.user_id)
.select(:upvotes, :downvotes)
.map {|c|
if base < 0
# in stories already starting out with a bad hotness mod, only look
# at the downvotes to find out if this tire fire needs to be put out
c.downvotes * -0.5
else
c.upvotes + 1 - c.downvotes
end
}
.inject(&:+).to_f * 0.5
sum_expression = base < 0 ? "downvotes * -0.5" : "upvotes + 1 - downvotes"
cpoints = self.merged_comments.where.not(user_id: self.user_id).sum(sum_expression).to_f * 0.5
# mix in any stories this one cannibalized
cpoints += self.merged_stories.map(&:score).inject(&:+).to_f

View File

@ -230,4 +230,32 @@ describe Story do
expect(s2.similar_stories).to eq([])
end
end
describe "#calculated_hotness" do
let(:story) do
create(:story, url: 'https://example.com', user_is_author: true, created_at: Time.zone.at(0))
end
before do
create(:comment, story: story, downvotes: 5, upvotes: 10)
create(:comment, story: story, downvotes: 10, upvotes: 5)
end
context "with positive base" do
it "return correct score" do
expect(story.calculated_hotness).to eq(-0.25)
end
end
context "with negative base" do
before do
tag = create(:tag, hotness_mod: -10)
story.update(tags: [tag])
end
it "return correct score" do
expect(story.calculated_hotness).to eq 9.75
end
end
end
end