DEV: Apply modifier for topic_view link_counts (#29883)

This commit is contained in:
Mark VanLandingham 2024-11-22 14:49:39 -06:00 committed by GitHub
parent 08440b0035
commit d880db3b7b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 45 additions and 16 deletions

View File

@ -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

View File

@ -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 }
after { DiscoursePluginRegistry.clear_modifiers! }
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
it "allows disabling of random suggested" do
topic_view = TopicView.new(topic1)
it "allows modifications to link_counts" do
expect(TopicView.new(topic).link_counts).to eq({})
Plugin::Instance
.new
.register_modifier(
:topic_view_suggested_topics_options,
) do |suggested_options, inner_topic_view|
expect(inner_topic_view).to eq(topic_view)
plugin.register_modifier(:topic_view_link_counts, &modifier)
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