return values from fork: fork_and_return

Very useful helper if you want to keep your environment clean, useful for testing or if you have to require something that has lots of side effects or memory leaks.

Usage

result = fork_and_return do
  require 'some_lib_with_side_effects'
  leak_some_memory
  get_stuff_done
end
puts result

Code

# https://grosser.it/2012/07/15/return-values-from-fork-fork_and_return/
def fork_and_return(&block)
  require 'parallel'
  Parallel.map([0], &block).first
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s