Class: Kward::Cancellation

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/cancellation.rb

Overview

Cooperative cancellation token shared by model calls, tools, and workers.

Defined Under Namespace

Classes: CancelledError

Instance Method Summary collapse

Constructor Details

#initializeCancellation

Returns a new instance of Cancellation.



10
11
12
13
14
# File 'lib/kward/cancellation.rb', line 10

def initialize
  @cancelled = false
  @callbacks = []
  @mutex = Mutex.new
end

Instance Method Details

#cancel!Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/kward/cancellation.rb', line 16

def cancel!
  callbacks = @mutex.synchronize do
    return if @cancelled

    @cancelled = true
    pending = @callbacks
    @callbacks = []
    pending
  end

  callbacks.each do |callback|
    callback.call
  rescue StandardError
    nil
  end
end

#cancelled?Boolean Also known as: canceled?

Returns:

  • (Boolean)


33
34
35
# File 'lib/kward/cancellation.rb', line 33

def cancelled?
  @mutex.synchronize { @cancelled }
end

#on_cancel(&block) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/kward/cancellation.rb', line 43

def on_cancel(&block)
  run_now = false
  @mutex.synchronize do
    if @cancelled
      run_now = true
    else
      @callbacks << block
    end
  end

  block.call if run_now
  nil
end

#raise_if_cancelled!Object

Raises:



39
40
41
# File 'lib/kward/cancellation.rb', line 39

def raise_if_cancelled!
  raise CancelledError, "cancelled" if cancelled?
end