Class: Notion::Batch

Inherits:
Object
  • Object
show all
Defined in:
lib/notion/batch.rb

Instance Method Summary collapse

Constructor Details

#initialize(concurrency) ⇒ Batch

Returns a new instance of Batch.



5
6
7
8
9
10
11
12
# File 'lib/notion/batch.rb', line 5

def initialize(concurrency)
  unless concurrency.is_a?(Integer) && concurrency.positive?
    raise ArgumentError, "concurrency must be a positive integer"
  end

  @concurrency = concurrency
  @jobs = []
end

Instance Method Details

#call(&job) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
18
19
# File 'lib/notion/batch.rb', line 14

def call(&job)
  raise ArgumentError, "a job block is required" unless job

  @jobs << job
  self
end

#runObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/notion/batch.rb', line 21

def run
  queue = Queue.new
  @jobs.each_with_index { |job, index| queue << [index, job] }
  results = Array.new(@jobs.length)
  errors = Array.new(@jobs.length)
  Array.new([@concurrency, @jobs.length].min) do
    Thread.new do
      while (entry = queue.pop(true))
        index, job = entry
        begin
          results[index] = job.call
        rescue StandardError => e
          errors[index] = e
        end
      end
    rescue ThreadError
      nil
    end
  end.each(&:join)
  raise errors.compact.first if errors.any?

  results
end