Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>We actually just had to handle this problem in <a href="http://github.com/rails/rails/blob/eea7b5db1db5d7e6020c5bcb6b4d85afcbc2e696/activesupport/lib/active_support/testing/isolation.rb#L37-54" rel="noreferrer">Rails isolation testing</a>. I posted about it some <a href="http://yehudakatz.com/2009/07/01/new-rails-isolation-testing/" rel="noreferrer">on my blog</a>.</p> <p>Basically, what you want to do is open a pipe in the parent and child, and have the child write to the pipe. Here's a simple way to run the contents of a block in a child process and get back the result:</p> <pre><code>def do_in_child read, write = IO.pipe pid = fork do read.close result = yield Marshal.dump(result, write) exit!(0) # skips exit handlers. end write.close result = read.read Process.wait(pid) raise "child failed" if result.empty? Marshal.load(result) end </code></pre> <p>Then you could run:</p> <pre><code>do_in_child do require "some_polluting_library" SomePollutingLibrary.some_operation end </code></pre> <p>Note that if you do a require in the child, you will not have access to that library in the parent, so you cannot return an object of that type using this method. However, you could return any type that's available in both.</p> <p>Also note that a lot of the details here (<code>read.close</code>, <code>Process.wait2(pid)</code>) are mostly housekeeping details, so if you use this a lot you should probably move this out into a utility library that you can reuse.</p> <p>Finally, note that this will not work on Windows or JRuby, since they don't support forking.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload