From 28ef5b2b46c2968380d7f1a7646797782738a33a Mon Sep 17 00:00:00 2001 From: Nat Date: Wed, 7 Aug 2024 16:46:46 +0800 Subject: [PATCH] FEATURE: Allow order:votes on /filter --- plugin.rb | 7 +++++++ spec/lib/topics_filter_spec.rb | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 spec/lib/topics_filter_spec.rb diff --git a/plugin.rb b/plugin.rb index 47408e6..79c1458 100755 --- a/plugin.rb +++ b/plugin.rb @@ -119,6 +119,13 @@ module ::DiscourseTopicVoting add_to_serializer(:current_user, :votes_count) { object.vote_count } add_to_serializer(:current_user, :votes_left) { [object.vote_limit - object.vote_count, 0].max } + filter_order_votes = ->(scope, order_direction) do + scope = scope.joins(:topic_vote_count) + scope.order("topic_voting_topic_vote_count.votes_count #{order_direction}") + end + + add_filter_custom_filter("order:votes", &filter_order_votes) + on(:topic_status_updated) do |topic, status, enabled| next if topic.trashed? next if %w[closed autoclosed archived].exclude?(status) diff --git a/spec/lib/topics_filter_spec.rb b/spec/lib/topics_filter_spec.rb new file mode 100644 index 0000000..7f7a0f0 --- /dev/null +++ b/spec/lib/topics_filter_spec.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +RSpec.describe TopicsFilter do + describe "when extending order:{col}" do + fab!(:topic_high) { Fabricate(:topic_voting_vote_count, votes_count: 10).topic } + fab!(:topic_med) { Fabricate(:topic_voting_vote_count, votes_count: 5).topic } + fab!(:topic_low) { Fabricate(:topic_voting_vote_count, votes_count: 1).topic } + + it "sorts votes in ascending order" do + expect( + TopicsFilter + .new(guardian: Guardian.new) + .filter_from_query_string("order:votes-asc") + .pluck(:id), + ).to eq([topic_low.id, topic_med.id, topic_high.id]) + end + + it "sorts votes in default descending order" do + expect( + TopicsFilter.new(guardian: Guardian.new).filter_from_query_string("order:votes").pluck(:id), + ).to eq([topic_high.id, topic_med.id, topic_low.id]) + end + end +end