2024-11-15 13:49:37 -05:00
|
|
|
module Syncable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
|
|
|
has_many :syncs, as: :syncable, dependent: :destroy
|
|
|
|
end
|
|
|
|
|
|
|
|
def syncing?
|
2025-05-15 10:19:56 -04:00
|
|
|
raise NotImplementedError, "Subclasses must implement the syncing? method"
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-26 05:39:14 -04:00
|
|
|
def sync_later(parent_sync: nil)
|
2025-05-17 18:28:21 -04:00
|
|
|
Sync.transaction do
|
2025-05-19 16:39:31 -04:00
|
|
|
with_lock do
|
|
|
|
sync = self.syncs.incomplete.first
|
2025-05-17 18:28:21 -04:00
|
|
|
|
2025-05-26 05:39:14 -04:00
|
|
|
unless sync
|
|
|
|
sync = self.syncs.create!(parent: parent_sync)
|
2025-05-19 16:39:31 -04:00
|
|
|
end
|
2025-05-18 10:19:15 -04:00
|
|
|
|
2025-05-26 05:39:14 -04:00
|
|
|
SyncJob.perform_later(sync)
|
|
|
|
|
2025-05-19 16:39:31 -04:00
|
|
|
sync
|
|
|
|
end
|
2025-05-17 18:28:21 -04:00
|
|
|
end
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-15 10:19:56 -04:00
|
|
|
def perform_sync(sync)
|
|
|
|
syncer.perform_sync(sync)
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-15 10:19:56 -04:00
|
|
|
def perform_post_sync
|
|
|
|
syncer.perform_post_sync
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-15 10:19:56 -04:00
|
|
|
def broadcast_sync_complete
|
|
|
|
sync_broadcaster.broadcast
|
2024-11-20 11:01:52 -05:00
|
|
|
end
|
|
|
|
|
2024-11-15 13:49:37 -05:00
|
|
|
def sync_error
|
2025-05-09 14:56:49 -04:00
|
|
|
latest_sync&.error
|
|
|
|
end
|
|
|
|
|
|
|
|
def last_synced_at
|
2025-05-15 10:19:56 -04:00
|
|
|
latest_sync&.completed_at
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-13 16:14:29 -04:00
|
|
|
def last_sync_created_at
|
|
|
|
latest_sync&.created_at
|
|
|
|
end
|
|
|
|
|
2025-05-26 05:39:14 -04:00
|
|
|
def needs_sync?
|
|
|
|
data_synced_through.nil? || data_synced_through < Date.current
|
|
|
|
end
|
|
|
|
|
2024-11-15 13:49:37 -05:00
|
|
|
private
|
|
|
|
def latest_sync
|
2025-05-15 10:19:56 -04:00
|
|
|
syncs.ordered.first
|
|
|
|
end
|
|
|
|
|
|
|
|
def syncer
|
|
|
|
self.class::Syncer.new(self)
|
|
|
|
end
|
|
|
|
|
|
|
|
def sync_broadcaster
|
|
|
|
self.class::SyncCompleteEvent.new(self)
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
end
|