Module: AcidicJob::Extensions::Noticed

Extended by:
ActiveSupport::Concern
Defined in:
lib/acidic_job/extensions/noticed.rb

Instance Method Summary collapse

Instance Method Details

#deliver_acidicly(recipients, unique_by: nil) ⇒ Object Also known as: deliver_transactionally



14
15
16
17
18
19
20
21
22
23
24
25
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
54
55
# File 'lib/acidic_job/extensions/noticed.rb', line 14

def deliver_acidicly(recipients, unique_by: nil)
  # THIS IS A HACK THAT COPIES AND PASTES KEY PARTS OF THE `Noticed::Base` CODE
  # IN ORDER TO ALLOW US TO TRANSACTIONALLY DELIVER NOTIFICATIONS
  # THIS IS THUS LIABLE TO BREAK WHENEVER THAT GEM IS UPDATED
  delivery_methods = self.class.delivery_methods.dup

  Array.wrap(recipients).uniq.each do |recipient|
    if (index = delivery_methods.find_index { |m| m[:name] == :database })
      database_delivery_method = delivery_methods.delete_at(index)
      self.record = run_delivery_method(database_delivery_method,
                                        recipient: recipient,
                                        enqueue: false,
                                        record: nil)
    end

    delivery_methods.map do |delivery_method|
      job_class = delivery_method_for(delivery_method[:name], delivery_method[:options])
      args = {
        notification_class: self.class.name,
        options: delivery_method[:options],
        params: params,
        recipient: recipient,
        record: record
      }
      serialized_job = job_class.send(:job_or_instantiate, args).serialize
      acidic_identifier = job_class.respond_to?(:acidic_identifier) ? job_class.acidic_identifier : :job_id
      # use either [1] provided uniqueness constraint or [2] computed key
      key = if unique_by
              IdempotencyKey.generate(unique_by: unique_by, job_class: job_class.name)
            else
              IdempotencyKey.new(acidic_identifier).value_for(serialized_job)
            end

      AcidicJob::Run.create!(
        staged: true,
        job_class: job_class.name,
        serialized_job: serialized_job,
        idempotency_key: key
      )
    end
  end
end