2022-11-30 20:32:35 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class SidebarSectionLinksUpdater
|
|
|
|
def self.update_category_section_links(user, category_ids:)
|
|
|
|
if category_ids.blank?
|
|
|
|
delete_section_links(user: user, linkable_type: "Category")
|
|
|
|
else
|
2023-07-26 22:52:33 -04:00
|
|
|
category_ids = Category.where(id: category_ids).pluck(:id)
|
2024-04-25 14:21:39 -04:00
|
|
|
category_ids = category_ids[...SidebarSection::MAX_USER_CATEGORY_LINKS]
|
2022-11-30 20:32:35 -05:00
|
|
|
update_section_links(user: user, linkable_type: "Category", new_linkable_ids: category_ids)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-07-26 22:52:33 -04:00
|
|
|
def self.update_tag_section_links(user, tag_ids:)
|
|
|
|
if tag_ids.blank?
|
2022-11-30 20:32:35 -05:00
|
|
|
delete_section_links(user: user, linkable_type: "Tag")
|
|
|
|
else
|
|
|
|
update_section_links(user: user, linkable_type: "Tag", new_linkable_ids: tag_ids)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.delete_section_links(user:, linkable_type:)
|
|
|
|
SidebarSectionLink.where(user: user, linkable_type: linkable_type).delete_all
|
|
|
|
end
|
|
|
|
private_class_method :delete_section_links
|
|
|
|
|
|
|
|
def self.update_section_links(user:, linkable_type:, new_linkable_ids:)
|
|
|
|
SidebarSectionLink.transaction do
|
|
|
|
existing_linkable_ids =
|
|
|
|
SidebarSectionLink.where(user: user, linkable_type: linkable_type).pluck(:linkable_id)
|
|
|
|
|
|
|
|
to_delete = existing_linkable_ids - new_linkable_ids
|
|
|
|
to_insert = new_linkable_ids - existing_linkable_ids
|
|
|
|
|
|
|
|
to_insert_attributes =
|
|
|
|
to_insert.map do |linkable_id|
|
|
|
|
{ linkable_type: linkable_type, linkable_id: linkable_id, user_id: user.id }
|
2023-01-09 07:20:10 -05:00
|
|
|
end
|
|
|
|
|
2022-11-30 20:32:35 -05:00
|
|
|
if to_delete.present?
|
|
|
|
SidebarSectionLink.where(
|
|
|
|
user: user,
|
|
|
|
linkable_type: linkable_type,
|
|
|
|
linkable_id: to_delete,
|
|
|
|
).delete_all
|
|
|
|
end
|
2023-07-26 22:52:33 -04:00
|
|
|
|
2022-11-30 20:32:35 -05:00
|
|
|
SidebarSectionLink.insert_all(to_insert_attributes) if to_insert_attributes.present?
|
|
|
|
end
|
|
|
|
end
|
|
|
|
private_class_method :update_section_links
|
|
|
|
end
|