Class: TableSync::Receiving::Hooks::Once

Inherits:
Object
  • Object
show all
Defined in:
lib/table_sync/receiving/hooks/once.rb

Constant Summary collapse

LOCK_KEY =
"hook-once-lock-key"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conditions:, handler:) ⇒ Once

Returns a new instance of Once.



9
10
11
12
13
# File 'lib/table_sync/receiving/hooks/once.rb', line 9

def initialize(conditions:, handler:)
  @conditions = conditions
  @handler = handler
  init_lookup_code
end

Instance Attribute Details

#conditionsObject (readonly)

Returns the value of attribute conditions.



7
8
9
# File 'lib/table_sync/receiving/hooks/once.rb', line 7

def conditions
  @conditions
end

#handlerObject (readonly)

Returns the value of attribute handler.



7
8
9
# File 'lib/table_sync/receiving/hooks/once.rb', line 7

def handler
  @handler
end

#lookup_codeObject (readonly)

Returns the value of attribute lookup_code.



7
8
9
# File 'lib/table_sync/receiving/hooks/once.rb', line 7

def lookup_code
  @lookup_code
end

Instance Method Details

#enabled?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/table_sync/receiving/hooks/once.rb', line 15

def enabled?
  conditions[:columns].any?
end

#perform(config:, targets:) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/table_sync/receiving/hooks/once.rb', line 19

def perform(config:, targets:)
  target_keys = config.option(:target_keys)
  model = config.model

  targets.each do |target|
    next unless conditions?(target)

    keys = target.slice(*target_keys)
    model.try_advisory_lock(prepare_lock_key(keys)) do
      model.find_and_save(keys:) do |entry|
        next unless allow?(entry)

        entry.hooks ||= []
        entry.hooks << lookup_code
        model.after_commit { handler.call(entry:) }
      end
    end
  end
end