FEATURE: Add on_preload for TopicView (#13122)
This allows plugins to load data on fetched posts before each post is individually serialized.
This commit is contained in:
parent
fc6e7dd3f1
commit
ca809d2c40
|
@ -4,6 +4,25 @@ class TopicView
|
|||
MEGA_TOPIC_POSTS_COUNT = 10000
|
||||
MIN_POST_READ_TIME = 4.0
|
||||
|
||||
def self.on_preload(&blk)
|
||||
(@preload ||= Set.new) << blk
|
||||
end
|
||||
|
||||
def self.cancel_preload(&blk)
|
||||
if @preload
|
||||
@preload.delete blk
|
||||
if @preload.length == 0
|
||||
@preload = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def self.preload(topic_view)
|
||||
if @preload
|
||||
@preload.each { |preload| preload.call(topic_view) }
|
||||
end
|
||||
end
|
||||
|
||||
attr_reader(
|
||||
:topic,
|
||||
:posts,
|
||||
|
@ -106,6 +125,8 @@ class TopicView
|
|||
end
|
||||
end
|
||||
|
||||
TopicView.preload(self)
|
||||
|
||||
@draft_key = @topic.draft_key
|
||||
@draft_sequence = DraftSequence.current(@user, @draft_key)
|
||||
|
||||
|
|
|
@ -15,6 +15,23 @@ describe TopicView do
|
|||
|
||||
let(:topic_view) { TopicView.new(topic.id, evil_trout) }
|
||||
|
||||
context "preload" do
|
||||
it "allows preloading of data" do
|
||||
preloaded_topic_view = nil
|
||||
preloader = lambda do |view|
|
||||
preloaded_topic_view = view
|
||||
end
|
||||
|
||||
TopicView.on_preload(&preloader)
|
||||
|
||||
expect(preloaded_topic_view).to eq(nil)
|
||||
topic_view
|
||||
expect(preloaded_topic_view).to eq(topic_view)
|
||||
|
||||
TopicView.cancel_preload(&preloader)
|
||||
end
|
||||
end
|
||||
|
||||
it "raises a not found error if the topic doesn't exist" do
|
||||
expect { TopicView.new(1231232, evil_trout) }.to raise_error(Discourse::NotFound)
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue