Refactor related content score methods to make them easier to follow

This commit is contained in:
Bertocq
2017-12-20 10:24:00 +01:00
parent f190d9c626
commit cf06d5b047
3 changed files with 27 additions and 15 deletions

View File

@@ -18,18 +18,18 @@ class RelatedContentsController < ApplicationController
end
def score_positive
score(1)
score(:positive)
end
def score_negative
score(-1)
score(:negative)
end
private
def score(value)
def score(action)
@related = RelatedContent.find_by(id: params[:id])
@related.score(value, current_user)
@related.send("score_#{action}", current_user)
render template: 'relationable/_refresh_score_actions'
end

View File

@@ -23,31 +23,38 @@ class RelatedContent < ActiveRecord::Base
scope :not_hidden, -> { where('positive_score - negative_score / LEAST(nullif(positive_score + negative_score, 0), 1) >= ?', RELATED_CONTENT_SCORE_THRESHOLD) }
scope :not_hidden, -> { where(hidden_at: nil) }
def score(value, user)
score_with_opposite(value, user)
hide_with_opposite if (related_content_scores.sum(:value) / self.related_content_scores_count) < RELATED_CONTENT_SCORE_THRESHOLD
def score_positive(user)
score(RelatedContentScore::SCORES[:POSITIVE], user)
end
def score_negative(user)
score(RelatedContentScore::SCORES[:NEGATIVE], user)
end
def scored_by_user?(user)
related_content_scores.where(user: user).count > 0
related_content_scores.exists?(user: user)
end
private
def hide_with_opposite
self.hide
opposite_related_content.hide
end
def create_opposite_related_content
related_content = RelatedContent.create!(opposite_related_content: self, parent_relationable: child_relationable,
child_relationable: parent_relationable, author: author)
self.opposite_related_content = related_content
end
def score(value, user)
score_with_opposite(value, user)
hide_with_opposite if (related_content_scores.sum(:value) / related_content_scores_count) < RELATED_CONTENT_SCORE_THRESHOLD
end
def hide_with_opposite
hide
opposite_related_content.hide
end
def create_author_score
score(1, author)
score_positive(author)
end
def score_with_opposite(value, user)

View File

@@ -1,4 +1,9 @@
class RelatedContentScore < ActiveRecord::Base
SCORES = {
POSITIVE: 1,
NEGATIVE: -1
}.freeze
belongs_to :related_content, touch: true, counter_cache: :related_content_scores_count
belongs_to :user