Skip to content

@timahoney /vm_contexts.rb
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A possible example of separate VM contexts in Ruby. This would be an alternative to using multiple processes.
#
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.