Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: Slowness when listing templates and the templates category #67

Merged
merged 2 commits into from Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 1 addition & 3 deletions lib/discourse_templates/topic_extension.rb
Expand Up @@ -28,9 +28,7 @@ def template?(user)
parent_categories_ids = SiteSetting.discourse_templates_categories&.split("|")&.map(&:to_i)

all_templates_categories_ids =
parent_categories_ids.flat_map do |category_id|
Category.subcategory_ids(category_id).prepend(category_id)
end
parent_categories_ids.flat_map { |category_id| Category.subcategory_ids(category_id) }

# it is template if the topic belongs to any of the template categories
return true if all_templates_categories_ids.include?(self.category_id)
Expand Down
29 changes: 29 additions & 0 deletions spec/lib/topic_extension_spec.rb
Expand Up @@ -112,5 +112,34 @@
expect(private_template_tag_b.template?(user)).to eq(true)
end
end

it "won't leak state into the Category.subcategory_ids cache" do
category = Fabricate(:category_with_definition)
subcategory = Fabricate(:category_with_definition, parent_category: category)
topic = Fabricate(:template_item, category: subcategory)
SiteSetting.discourse_templates_categories = category.id.to_s

# assert that the return of Category.subcategory_ids is what we expect before
# calling template? on the topic
expect(Category.subcategory_ids(category.id).size).to eq(2)
expect(Category.subcategory_ids(category.id)).to contain_exactly(category.id, subcategory.id)

expect(topic.template?(user)).to eq(true)

# the return of Category.subcategory_ids is what was not changed by the call to template?
expect(Category.subcategory_ids(category.id).size).to eq(2)
expect(Category.subcategory_ids(category.id)).to contain_exactly(category.id, subcategory.id)

# Now we'll change the category of the topic to a category that is not a template category
topic.update!(category: Fabricate(:category))

# The cache should be invalidated and the topic should no longer be considered a template
expect(topic.template?(user)).to eq(false)

# the return of Category.subcategory_ids is also not changed by the call to template? in a topic
# that is not a template
expect(Category.subcategory_ids(category.id).size).to eq(2)
expect(Category.subcategory_ids(category.id)).to contain_exactly(category.id, subcategory.id)
end
end
end