Class: Kward::Cancellation

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

Defined Under Namespace

Classes: CancelledError

Instance Method Summary collapse

Constructor Details

#initializeCancellation

Returns a new instance of Cancellation.



7
8
9
10
11
# File 'lib/kward/cancellation.rb', line 7

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

Instance Method Details

#cancel!Object



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

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)


30
31
32
# File 'lib/kward/cancellation.rb', line 30

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

#on_cancel(&block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/kward/cancellation.rb', line 40

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:



36
37
38
# File 'lib/kward/cancellation.rb', line 36

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