Class: Consyncful::Sync

Inherits:
Object
  • Object
show all
Includes:
Hooks, Mongoid::Document
Defined in:
lib/consyncful/sync.rb

Overview

A mongoid model that stores the state of a syncronisation feed. Stores the next URL provided by Contentfuls Sync API.

Sync’s are affectivly singletons, there should only ever be one in the database

Is also the entrypoint of a Syncronization run

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.consume_webhook_signal!Object

Consume the webhook signal and set webhook_pending to false



45
46
47
48
49
50
# File 'lib/consyncful/sync.rb', line 45

def self.consume_webhook_signal!
  return false unless latest.webhook_pending?

  latest.set(webhook_pending: false)
  true
end

.freshObject

Delete the previous sync chains from database and create a fresh one. Used to completely resync all items from Contentful.



55
56
57
58
# File 'lib/consyncful/sync.rb', line 55

def self.fresh
  destroy_all
  latest
end

.latestObject



32
33
34
# File 'lib/consyncful/sync.rb', line 32

def self.latest
  last || new
end

.signal_webhook!Object

Signal that a webhook has been received and a sync should be triggered



38
39
40
41
# File 'lib/consyncful/sync.rb', line 38

def self.signal_webhook!
  latest.set(webhook_pending: true)
  true
end

Instance Method Details

#drop_staleObject

Makes sure that the database contains only records that have been provided during this chain of syncronisation.



63
64
65
66
67
# File 'lib/consyncful/sync.rb', line 63

def drop_stale
  stale = Base.where(:sync_id.ne => id, :sync_id.exists => true)
  puts Rainbow("Dropping #{stale.count} records that haven't been touched in this sync").red
  stale.destroy
end

#runObject

Entry point to a syncronization run. Is responsible for updating Sync state



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/consyncful/sync.rb', line 71

def run
  run_hook :before_run

  stats = Consyncful::Stats.new
  load_all_models

  sync = start_sync

  changed_ids = sync_items(sync, stats)

  drop_stale

  update_run(sync.next_sync_url)
  stats.print_stats

  run_hook :after_run, changed_ids
end