Module: Interruptible

Defined in:
lib/interruptible.rb,
lib/interruptible/version.rb

Overview

Copyright 2019 Michal Papis <[email protected]>

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.

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =

Version of Interruptible

"1.0.0".freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



20
21
22
# File 'lib/interruptible.rb', line 20

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#interrupt(signal = :interrupt) ⇒ Object

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



41
42
43
# File 'lib/interruptible.rb', line 41

def interrupt(signal = :interrupt)
  throw signal
end

#interruptible(signal = :interrupt) ⇒ Object

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



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 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