Class: AngryBatch::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/angry_batch/builder.rb

Instance Method Summary collapse

Constructor Details

#initialize(label: nil, metadata: {}) ⇒ Builder

Returns a new instance of Builder.



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/angry_batch/builder.rb', line 4

def initialize(label: nil, metadata: {})
  @metadata = ActiveJob::Arguments.serialize([ || {}]).first
  @batch = AngryBatch::Batch.new(
    label: label,
    metadata: @metadata,
    complete_handlers: [],
    failure_handlers: [],
  )
  @jobs = []
  @performed = false
end

Instance Method Details

#enqueue(job_class) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/angry_batch/builder.rb', line 38

def enqueue(job_class, *, **)
  raise AngryBatch::BatchArgumentError, 'Batch is already running' if performed?

  AngryBatch::Helper.assert_batchable(job_class)

  @jobs << job_class.new(*, **)
end

#on_complete(job_class) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/angry_batch/builder.rb', line 22

def on_complete(job_class, *, **)
  raise AngryBatch::BatchArgumentError, 'Batch is already running' if performed?

  AngryBatch::Helper.assert_job_class(job_class)

  @batch.complete_handlers << [job_class, job_class.new(*, **).serialize['arguments']]
end

#on_failure(job_class) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/angry_batch/builder.rb', line 30

def on_failure(job_class, *, **)
  raise AngryBatch::BatchArgumentError, 'Batch is already running' if performed?

  AngryBatch::Helper.assert_job_class(job_class)

  @batch.failure_handlers << [job_class, job_class.new(*, **).serialize['arguments']]
end

#perform_laterObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/angry_batch/builder.rb', line 46

def perform_later
  raise AngryBatch::BatchArgumentError, 'Batch is empty' if empty?
  raise AngryBatch::BatchArgumentError, 'Batch is already running' if performed?

  ActiveRecord::Base.transaction(requires_new: true) do
    @batch.save!

    @jobs.each { |job| AngryBatch::Helper.add_job_to_batch(@batch, job) }
  end

  @performed = true

  AngryBatch::Helper.after_transaction do
    @jobs.each do |job|
      raise ActiveJob::EnqueueError, ["#{job.class.name} was not enqueued", job.enqueue_error&.message].compact.join(': ') unless job.enqueue
    end
  end

  @batch
rescue StandardError
  unless @performed
    @batch = AngryBatch::Batch.new(
      label: @batch.label,
      metadata: @metadata,
      complete_handlers: @batch.complete_handlers,
      failure_handlers: @batch.failure_handlers,
    )
  end
  raise
end

#performed?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/angry_batch/builder.rb', line 16

def performed?
  @performed
end