Estou tentando encontrar uma maneira de fazer com que as tags criadas por usuários em uma categoria específica sejam automaticamente atribuídas a um grupo de tags especificado. Pesquisei e não encontrei nada disponível atualmente.
Este código parece que faria o que eu quero?
enabled_site_setting :auto_tag_to_group_enabled
# Plugin settings
register_site_setting :auto_tag_to_group_enabled, default: true
register_site_setting :auto_tag_category_name, default: "RestrictedCategory"
register_site_setting :auto_tag_group_name, default: "RestrictedTags"
after_initialize do
module ::DiscourseAutoTagToGroup
class Engine
engine_name "discourse_auto_tag_to_group"
isolate_namespace DiscourseAutoTagToGroup
end
end
require_dependency "topic"
class ::Topic
after_save :auto_assign_new_tags_to_group, if: :auto_tag_to_group_conditions_met?
private
def auto_tag_to_group_conditions_met?
# Check if plugin is enabled and topic has tags
SiteSetting.auto_tag_to_group_enabled
end
def auto_assign_new_tags_to_group
# Get the configured category and tag group names
target_category_name = SiteSetting.auto_tag_category_name
target_tag_group_name = SiteSetting.auto_tag_group_name
# Find the category and tag group
target_category = Category.find_by(name: target_category_name)
target_tag_group = TagGroup.find_by(name: target_tag_group_name)
# Exit if category or tag group not found
return unless target_category
return unless self.category_id == target_category.id
# Get the timestamp of the topic creation
topic_created_at = self.created_at
self.tags.each do |tag|
# Check if the tag was created close to the topic creation time
# Allow a small window (e.g., 1 minute) to account for processing delays
if tag.created_at
# Check if tag is already in the target tag group
unless TagGroupMembership.exists?(tag_id: tag.id, tag_group_id: target_tag_group.id)
# Add the tag to the tag group
TagGroupMembership.create!(tag_id: tag.id, tag_group_id: target_tag_group.id)
end
end
end
end
end
end