module Interruptible

Extension of throw/catch to preserve interruption when once interrupted with given signal.

Copyright 2019 Michal Papis <mpapis@gmail.com>

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Constants

VERSION

Version of Interruptible

Public Class Methods

included(base) click to toggle source
# File lib/interruptible.rb, line 20
def self.included(base)
  base.extend ClassMethods
end

Public Instance Methods

interrupt(signal = :interrupt) click to toggle source

Fancy way to say `throw`, defined for consistent naming. It will throw a signal for the `interruptible` to catch.

# File lib/interruptible.rb, line 41
def interrupt(signal = :interrupt)
  throw signal
end
interruptible(signal = :interrupt) { || ... } click to toggle source

Wraps a `catch` in a way that allows it to be persisted for all other instances where the code should be interrupted.

# File lib/interruptible.rb, line 47
def interruptible(signal = :interrupt)
  flag = instance_variable_get("@interrupted_#{signal}")
  return if flag
  result = nil
  flag =
    catch(signal) do
      result = yield
      true
      # when stopped catch returns nil, othervise it returns the last value,
      # we are using the true to signal it executed without interruption,
      # thus when we save the flag we use the negation
    end
  instance_variable_set("@interrupted_#{signal}", true) unless flag
  result
end