Class: EmbeddedAssets::SyncService

Inherits:
Object
  • Object
show all
Defined in:
app/services/embedded_assets/sync_service.rb

Overview

Synchronizes EmbeddedAsset records with the actual content of a parent record.

When content is saved, this service:

  1. Parses the HTML content to find all data-embedded-asset-uuid attributes
  2. Deletes any EmbeddedAsset records that are no longer in the content
  3. Returns statistics about what was synced

Usage:
result = EmbeddedAssets::SyncService.new(article).call
result # => { found: 5, orphaned: 2, deleted: 2 }

The service is idempotent and safe to call multiple times.

Constant Summary collapse

UUID_SELECTOR =

CSS selector for finding embedded asset UUIDs in content

'[data-embedded-asset-uuid]'

Instance Method Summary collapse

Constructor Details

#initialize(parent, options = {}) ⇒ SyncService

Returns a new instance of SyncService.



21
22
23
24
# File 'app/services/embedded_assets/sync_service.rb', line 21

def initialize(parent, options = {})
  @parent = parent
  @options = options
end

Instance Method Details

#callObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'app/services/embedded_assets/sync_service.rb', line 26

def call
  return { found: 0, orphaned: 0, deleted: 0, skipped: true } unless parent.present?

  content_uuids = extract_uuids_from_content
  existing_uuids = parent.embedded_assets.pluck(:uuid)

  orphaned_uuids = existing_uuids - content_uuids
  orphaned_count = orphaned_uuids.size

  deleted_count = 0
  if orphaned_uuids.any?
    deleted_count = parent.embedded_assets.where(uuid: orphaned_uuids).delete_all
    Rails.logger.info("[EmbeddedAssets::SyncService] Deleted #{deleted_count} orphaned assets for #{parent.class.name}##{parent.id}")
  end

  # Within-widget FAQ pruning: a FAQ widget's UUID stays in the HTML even
  # when individual FAQs are removed from data-faq-ids. Sync the individual
  # EmbeddedFaqAsset records against the actual data-faq-ids attribute.
  faq_pruned = prune_faq_widget_orphans
  deleted_count += faq_pruned

  {
    found: content_uuids.size,
    orphaned: orphaned_count,
    deleted: deleted_count,
    faq_pruned: faq_pruned
  }
end