Skip to content
This repository was archived by the owner on Jul 22, 2025. It is now read-only.
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 19 additions & 10 deletions lib/sentiment/emotion_filter_order.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,31 @@ class EmotionFilterOrder
def self.register!(plugin)
Emotions::LIST.each do |emotion|
filter_order_emotion = ->(scope, order_direction) do
scope_period =
scope
.arel
.constraints
.flat_map(&:children)
.find do |node|
node.is_a?(Arel::Nodes::Grouping) &&
node.expr.to_s.match?(/topics\.bumped_at\s*>=/)
end
&.expr
&.split(">=")
&.last

# Fallback in case we can't find the scope period
scope_period ||= "CURRENT_DATE - INTERVAL '1 year'"

emotion_clause = <<~SQL
SUM(
CASE
WHEN (classification_results.classification::jsonb->'#{emotion}')::float > 0.1
THEN 1
ELSE 0
END
)::float / COUNT(posts.id)
COUNT(*) FILTER (WHERE (classification_results.classification::jsonb->'#{emotion}')::float > 0.1) AS emotion_#{emotion}
SQL

# TODO: This is slow, we will need to materialize this in the future
with_clause = <<~SQL
SELECT
topics.id,
#{emotion_clause} AS emotion_#{emotion}
#{emotion_clause}
FROM
topics
INNER JOIN
Expand All @@ -35,10 +45,9 @@ def self.register!(plugin)
AND topics.deleted_at IS NULL
AND posts.deleted_at IS NULL
AND posts.post_type = 1
AND posts.created_at >= #{scope_period}
GROUP BY
1
HAVING
#{emotion_clause} > 0.05
SQL

scope
Expand Down
Loading