Class: Mutiny::Isolation

Inherits:
Object
  • Object
show all
Defined in:
lib/mutiny/isolation.rb,
lib/mutiny/isolation/pipe.rb,
lib/mutiny/isolation/vacuum.rb

Overview

This code originally based on Markus Schirp’s implementation of Mutant::Isolation::Fork

https://github.com/mbj/mutant/blob/master/lib/mutant/isolation.rb

Defined Under Namespace

Classes: Pipe, Vacuum

Constant Summary collapse

Error =
Class.new(RuntimeError)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(isolated_code) ⇒ Isolation

Returns a new instance of Isolation.



18
19
20
# File 'lib/mutiny/isolation.rb', line 18

def initialize(isolated_code)
  @isolated_code = isolated_code
end

Instance Attribute Details

#isolated_codeObject (readonly)

Returns the value of attribute isolated_code.



16
17
18
# File 'lib/mutiny/isolation.rb', line 16

def isolated_code
  @isolated_code
end

Class Method Details

.call(&block) ⇒ Object

Runs the given block, isolating the global state so that changes cannot leak out to the caller’s runtime



10
11
12
13
14
# File 'lib/mutiny/isolation.rb', line 10

def self.call(&block)
  new(block).run_in_isolation
rescue => exception
  raise Error, exception
end

Instance Method Details

#run_and_send_result_via(comms) ⇒ Object



33
34
35
36
37
38
# File 'lib/mutiny/isolation.rb', line 33

def run_and_send_result_via(comms)
  Vacuum.silence($stderr) do
    result = isolated_code.call
    comms.send(result) # send the result to the parent process over the pipes
  end
end

#run_in_isolationObject



22
23
24
25
26
27
28
29
30
31
# File 'lib/mutiny/isolation.rb', line 22

def run_in_isolation
  Pipe.with do |comms|
    begin
      pid = Process.fork { run_and_send_result_via(comms) }
      comms.receive # wait to receive the result form the child process
    ensure
      Process.waitpid(pid) if pid
    end
  end
end