public
Last active

A possible example of separate VM contexts in Ruby. This would be an alternative to using multiple processes.

  • Download Gist
vm_contexts.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#
# The main world out here represents the default Context.
# Each Context is its own environment.
$name = 'Main Context'
context_a = VMContext.new
context_a.eval do
puts $name # nil. Globals are not shared.
$name = 'Context A'
puts $name # Context A
end
puts $name # Main Context
 
 
 
#
# Classes are also not shared.
# You can be sure your classes are safe from unwanted modification.
class MyClass
def print_me
puts $name
end
end
 
MyClass.new.print_me # Main Context
 
context_a.eval do
MyClass.new.print_me # Raises exception. MyClass doesn't exist.
class MyClass
def print_me
puts $name
end
end
MyClass.new.print_me # Context A
end
 
 
 
#
# You can send arbitrary data between Contexts.
# In this case, we'll send a hash that tells
# the Context to do something.
context_a.on_receive do |message|
case message[:type]
when :print_my_class
MyClass.new.print_me
when :new_name
$name = message[:value]
when :main_context_print
message[:value].eval { MyClass.new.print_me }
end
end
 
eval_message = { :type => :print_my_class }
new_name_message = { :type => :new_name,
:value => 'Context A (from Main)' }
context_a.send(eval_message) # Context A
context_a.send(new_name_message)
context_a.send(eval_message) # Context A (from Main)
 
context_main = VMContext.current
main_context_message = { :type => :main_context_print,
:value => context_main }
context_a.send(main_context_message) # Main Context

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.