Class: Clockwork::DatabaseEvents::SyncPerformer

Inherits:
Object
  • Object
show all
Defined in:
lib/clockwork/database_events/sync_performer.rb

Constant Summary collapse

PERFORMERS =
[]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_class, &proc) ⇒ SyncPerformer

Returns a new instance of SyncPerformer.


23
24
25
26
27
28
29
# File 'lib/clockwork/database_events/sync_performer.rb', line 23

def initialize(model_class, &proc)
  @model_class = model_class
  @block = proc
  @database_event_registry = Registry.new

  PERFORMERS << self
end

Class Method Details

.setup(options = {}, &block) ⇒ Object


11
12
13
14
15
16
17
18
19
20
21
# File 'lib/clockwork/database_events/sync_performer.rb', line 11

def self.setup(options={}, &block)
  model_class = options.fetch(:model) { raise KeyError, ":model must be set to the model class" }
  every = options.fetch(:every) { raise KeyError, ":every must be set to the database sync frequency" }

  sync_performer = self.new(model_class, &block)

  # create event that syncs clockwork events with events coming from database-backed model
  Clockwork.manager.every every, "sync_database_events_for_model_#{model_class}" do
    sync_performer.sync
  end
end

Instance Method Details

#register(event, model) ⇒ Object

delegates to Registry


32
33
34
# File 'lib/clockwork/database_events/sync_performer.rb', line 32

def register(event, model)
  @database_event_registry.register(event, model)
end

#syncObject

Ensure clockwork events reflect events from database-backed model Adds any new events, modifies updated ones, and delets removed ones


38
39
40
41
42
43
44
45
46
47
48
# File 'lib/clockwork/database_events/sync_performer.rb', line 38

def sync
  model_ids_that_exist = []

  @model_class.all.each do |model|
    model_ids_that_exist << model.id
    if are_different?(@database_event_registry.event_for(model), model)
      create_or_recreate_event(model)
    end
  end
  @database_event_registry.unregister_all_except(model_ids_that_exist)
end