FEATURE: respect tags_sort_alphabetically setting when display tags (#10889)

FEATURE: respect tags_sort_alphabetically setting when display tags (#10889)

Currently, tag labels are displayed in random order.

They should be displayed in alphabetical or popularity order based on SiteSetting (tags_sort_alphabetically)

Meta: https://meta.discourse.org/t/how-to-apply-tag-sorts-by-popularity-to-topic-list-currently-it-seems-only-apply-to-tag-page/163186/7

diff --git a/app/serializers/concerns/topic_tags_mixin.rb b/app/serializers/concerns/topic_tags_mixin.rb
index 5884118..990f8ad 100644
--- a/app/serializers/concerns/topic_tags_mixin.rb
+++ b/app/serializers/concerns/topic_tags_mixin.rb
@@ -11,7 +11,8 @@ module TopicTagsMixin
 
   def tags
     # Calling method `pluck` along with `includes` causing N+1 queries
-    tags = topic.tags.map(&:name)
+    order_setting = SiteSetting.tags_sort_alphabetically ? { name: :asc } : { topic_count: :desc }
+    tags = topic.tags.order(order_setting).map(&:name)
 
     if scope.is_staff?
       tags
diff --git a/spec/serializers/topic_view_serializer_spec.rb b/spec/serializers/topic_view_serializer_spec.rb
index 3262da2..855dbc7 100644
--- a/spec/serializers/topic_view_serializer_spec.rb
+++ b/spec/serializers/topic_view_serializer_spec.rb
@@ -212,6 +212,30 @@ describe TopicViewSerializer do
     end
   end
 
+  describe 'tags order' do
+    fab!(:tag1) { Fabricate(:tag, name: 'ctag', topic_count: 5) }
+    fab!(:tag2) { Fabricate(:tag, name: 'btag', topic_count: 9) }
+    fab!(:tag3) { Fabricate(:tag, name: 'atag', topic_count: 3) }
+
+    before do
+      SiteSetting.tagging_enabled = true
+      topic.tags << tag1
+      topic.tags << tag2
+      topic.tags << tag3
+    end
+
+    it 'tags are automatically sorted by tag popularity' do
+      json = serialize_topic(topic, user)
+      expect(json[:tags]).to eq(%w(btag ctag atag))
+    end
+
+    it 'tags can be sorted alphabetically' do
+      SiteSetting.tags_sort_alphabetically = true
+      json = serialize_topic(topic, user)
+      expect(json[:tags]).to eq(%w(atag btag ctag))
+    end
+  end
+
   context "with flags" do
     fab!(:post) { Fabricate(:post, topic: topic) }
     fab!(:other_post) { Fabricate(:post, topic: topic) }

GitHub sha: 6be60b0a

This commit appears in #10889 which was approved by gschlager. It was merged by lis2.