Ruby::Box: isolated namespaces

suggest change

Everything you require in Ruby goes into one global space. If a gem reopens String, every other gem in the process sees that method. If two gems define a top-level Money constant, the second require reopens the first one's module. And you can't load two versions of the same library side by side.

Ruby 4.0 adds an experimental feature called Ruby Box (the Ruby::Box class), which splits a single process into separate spaces. Code loaded into a box gets its own:

All the output below comes from Ruby 4.0.7 (RubyInstaller, x64-mingw-ucrt). Read "A warning for Windows users" below before you try this on your own machine.

For loading files the normal way, see Loading Source Files. For the problems boxes are meant to solve, see Monkey patching in Ruby and Refinements.

Enabling Ruby::Box

Boxes are off by default. To turn them on, set the RUBY_BOX environment variable to 1 before Ruby starts. 1 is the only value that works. Any other value, or no value, leaves boxes off, and setting ENV["RUBY_BOX"] from inside a running program has no effect.

The Ruby::Box class exists either way, so you can check whether boxes are on:

p defined?(Ruby::Box)
p Ruby::Box.enabled?
$ ruby check.rb
"constant"
false

Creating a box while the feature is off raises an error:

$ ruby -e 'Ruby::Box.new'
-e:1:in 'Ruby::Box#initialize': Ruby Box is disabled. Set RUBY_BOX=1 environment variable to use Ruby::Box. (RuntimeError)
	from -e:1:in '<main>'

With the variable set, Ruby prints an experimental warning at startup:

p Ruby::Box.enabled?
p Ruby::Box.current
p Ruby::Box.main
p Ruby::Box.root
b = Ruby::Box.new
p b
p Ruby::Box.instance_methods(false).sort
p Ruby::Box.singleton_methods.sort
$ RUBY_BOX=1 ruby boxes.rb
C:\Ruby40-x64\bin\ruby.exe: warning: Ruby::Box is experimental, and the behavior may change in the future!
See https://docs.ruby-lang.org/en/4.0/Ruby/Box.html for known issues, etc.
true
#<Ruby::Box:3,user,main>
#<Ruby::Box:3,user,main>
#<Ruby::Box:2,root>
#<Ruby::Box:4,user,optional>
[:eval, :inspect, :load, :load_path, :main?, :master?, :require, :require_relative, :root?]
[:constants, :current, :enabled?, :main, :master, :nesting, :root, :used_modules, :used_refinements]

To hide the warning, pass -W:no-experimental. The other examples in this article do that. In PowerShell, set the variable with $env:RUBY_BOX = "1" and in cmd.exe with set RUBY_BOX=1.

The output shows the kinds of boxes:

Ruby::Box is a subclass of Module, so a box behaves like a module that holds its own top-level constants.

Loading code into a box

Here's a library file that does several things that usually affect the whole process. It patches String, sets a global variable and defines top-level constants:

# patch.rb
class String
  def shout = upcase + "!"
end
$greeting = "hello from patch.rb"
VERSION_TAG = "v1"
module Greeter
  def self.greet(name) = "Hi, #{name}".shout
end

Load it into a new box and look around from the main box:

box = Ruby::Box.new
box.require_relative "patch"
p box::Greeter.greet("ann")
p "x".respond_to?(:shout)
p defined?(Greeter)
p $greeting
p box::VERSION_TAG
p box.eval('"abc".shout')
p box.eval('$greeting')
p box.load_path.size, $LOAD_PATH.size
p Ruby::Box.current
p box.eval('Ruby::Box.current')
p box.main?, box.root?
$ RUBY_BOX=1 ruby -W:no-experimental t1.rb
"HI, ANN!"
false
nil
nil
"v1"
"ABC!"
"hello from patch.rb"
8
8
#<Ruby::Box:3,user,main>
#<Ruby::Box:4,user,optional>
false
false

Line by line:

Boxes work per file. A .rb file runs in exactly one box, and every method, block and proc it defines keeps running in that box, no matter who calls it.

How built-in classes behave in a box

There's only one String class. box::String and String are the same object, and objects pass between boxes freely. What differs per box is the class's contents:

Boxes also have side effects you may not expect:

Two versions of one library

Sometimes two parts of an app need incompatible versions of the same library. Normally Ruby can't load both, because the second require reopens the module the first one defined. With boxes, each version can live in its own box. Here are two versions of a money library:

# vendor/money-1/lib/money.rb
module Money
  VERSION = "1.4.0"
  def self.format(cents) = "$#{cents / 100}.#{format_cents(cents)}"
  def self.format_cents(cents) = (cents % 100).to_s.rjust(2, "0")
end
# vendor/money-2/lib/money.rb
module Money
  VERSION = "2.0.1"
  Amount = Data.define(:cents, :currency) do
    def to_s = "#{currency} #{format("%.2f", cents / 100.0)}"
  end
  def self.format(cents, currency: "USD") = Amount.new(cents, currency).to_s
end

Give each box its own load path, then call require as usual:

old = Ruby::Box.new
old.load_path << File.expand_path("vendor/money-1/lib", __dir__)
old.require "money"

new = Ruby::Box.new
new.load_path << File.expand_path("vendor/money-2/lib", __dir__)
new.require "money"

p old::Money::VERSION
p new::Money::VERSION
puts old::Money.format(1999)
puts new::Money.format(1999, currency: "EUR")
p defined?(Money)
p old::Money.equal?(new::Money)
p $LOAD_PATH.grep(/money/)
p old.load_path.grep(/money/).map { File.basename(File.dirname(_1)) }
amount = new::Money::Amount.new(500, "PLN")
p amount
p amount.class
p amount.is_a?(Data)
$ RUBY_BOX=1 ruby -W:no-experimental two.rb
"1.4.0"
"2.0.1"
$19.99
EUR 19.99
nil
false
[]
["money-1"]
#<data Money::Amount cents=500, currency="PLN">
Money::Amount
true

$LOADED_FEATURES is per box too. Requiring a file in one box doesn't stop it from loading again in another box, so a file required in three boxes runs three times.

Sandboxing plugins

The other main use case is loading third-party plugins without letting their monkey patches and globals leak into your app. This sketch only combines calls from the examples above (Ruby::Box.new, require with an absolute path, const_get), but it wasn't run, for the reason in the next section:

class PluginHost
  Plugin = Struct.new(:name, :box, :entry)

  def initialize = @plugins = []

  # Each plugin file must define a top-level module named after the file.
  def load_plugin(path)
    name = File.basename(path, ".rb").split("_").map(&:capitalize).join
    box = Ruby::Box.new
    box.require(File.expand_path(path))
    @plugins << Plugin.new(name, box, box.const_get(name))
  end

  def run(event, payload)
    @plugins.map { |pl| pl.entry.handle(event, payload) }
  end
end

Each plugin gets a fresh box, so one plugin can redefine String#blank? or set $VERBOSE = nil without the host or other plugins noticing. A box isn't a security sandbox, though. Plugin code can still read files, open sockets, call exit, and use ObjectSpace or Ruby::Box.main to reach objects outside its box. It isolates names, not privileges. For a plain plugin registry without boxes, see Plugins and extensions.

A warning for Windows users

On the Windows machine used for this article (RubyInstaller 4.0.7-1 x64), running boxes damaged the Ruby installation. Ruby::Box loads native extensions (.so files) separately in each box. After a few RUBY_BOX=1 runs, five extension files had disappeared from C:\Ruby40-x64\lib\ruby\4.0.0\x64-mingw-ucrt: monitor.so, enc/utf_16le.so, enc/trans/single_byte.so, enc/trans/utf_16_32.so and win32/dll_directory.so. After that, every ruby command failed at startup, with or without RUBY_BOX:

C:/Ruby40-x64/lib/ruby/4.0.0/monitor.rb:10:in 'Kernel#require': cannot load such file -- monitor.so (LoadError)
	from C:/Ruby40-x64/lib/ruby/4.0.0/monitor.rb:10:in '<top (required)>'
	from C:/Ruby40-x64/lib/ruby/4.0.0/rubygems.rb:1457:in '<top (required)>'

Copying the files back from the RubyInstaller .7z archive fixes the install. Until this is fixed, try Ruby::Box only in a throwaway Ruby install or a container, never in the Ruby you use for real work.

Limitations

Ruby::Box is a preview of an idea, not a feature to ship with. The 4.0 documentation lists these known issues and open questions:

Because this is experimental, the API (Ruby::Box, RUBY_BOX, the box kinds) may change or be renamed in later releases. If what you need is one patch confined to your own code, Refinements work in every Ruby version today.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents