Skip to content

A platform for community discussion. Free, open, simple.

DEV: Apply modifier for topic_view link_counts (#29883)

Mark VanLandinghamd880db3b7b74
diff --git a/lib/topic_view.rb b/lib/topic_view.rb
index 16aed2f74f7..f7e4745997d 100644
--- a/lib/topic_view.rb
+++ b/lib/topic_view.rb
@@ -684,7 +684,15 @@ class TopicView
end
def link_counts
- @link_counts ||= TopicLink.counts_for(@guardian, @topic, posts)
+ # Normal memoizations doesn't work in nil cases, so using the ol' `defined?` trick
+ # to memoize more safely, as a modifier could nil this out.
+ return @link_counts if defined?(@link_counts)
+
+ @link_counts =
+ DiscoursePluginRegistry.apply_modifier(
+ :topic_view_link_counts,
+ TopicLink.counts_for(@guardian, @topic, posts),
+ )
end
def pm_params
diff --git a/spec/lib/topic_view_spec.rb b/spec/lib/topic_view_spec.rb
index b4789fb92d8..dfb49f39b30 100644
--- a/spec/lib/topic_view_spec.rb
+++ b/spec/lib/topic_view_spec.rb
@@ -1123,29 +1123,50 @@ RSpec.describe TopicView do
end
end
- describe "with topic_view_suggested_topics_options modifier" do
- let!(:topic1) { Fabricate(:topic) }
- let!(:topic2) { Fabricate(:topic) }
+ describe "plugin modifiers" do
+ let(:plugin) { Plugin::Instance.new }
+
+ context "with topic_view_link_counts modifier registered" do
+ let(:modifier) do
+ Proc.new do |link_counts|
+ link_counts["hijacked hehe"] = true
+ link_counts
+ end
+ end
- after { DiscoursePluginRegistry.clear_modifiers! }
+ it "allows modifications to link_counts" do
+ expect(TopicView.new(topic).link_counts).to eq({})
- it "allows disabling of random suggested" do
- topic_view = TopicView.new(topic1)
+ plugin.register_modifier(:topic_view_link_counts, &modifier)
- Plugin::Instance
- .new
- .register_modifier(
- :topic_view_suggested_topics_options,
- ) do |suggested_options, inner_topic_view|
- expect(inner_topic_view).to eq(topic_view)
+ expect(TopicView.new(topic).link_counts).to eq({ "hijacked hehe" => true })
+ ensure
+ DiscoursePluginRegistry.unregister_modifier(plugin, :topic_view_link_counts, &modifier)
+ end
+ end
+
+ context "with topic_view_suggested_topics_options modifier" do
+ let!(:topic1) { Fabricate(:topic) }
+ let!(:topic2) { Fabricate(:topic) }
+ let(:modifier) do
+ Proc.new do |suggested_options, inner_topic_view|
suggested_options.merge(include_random: false)
end
+ end
- expect(topic_view.suggested_topics.topics.count).to eq(0)
+ it "allows modifications to suggested topics (disabling of random suggested)" do
+ expect(TopicView.new(topic1).suggested_topics.topics.count).to be > 0
- DiscoursePluginRegistry.clear_modifiers!
+ plugin.register_modifier(:topic_view_suggested_topics_options, &modifier)
- expect(TopicView.new(topic1).suggested_topics.topics.count).to be > 0
+ expect(TopicView.new(topic1).suggested_topics.topics.count).to eq(0)
+ ensure
+ DiscoursePluginRegistry.unregister_modifier(
+ plugin,
+ :topic_view_suggested_topics_options,
+ &modifier
+ )
+ end
end
end
end