Ruby::Box: isolated namespaces
suggest changeEverything 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:
- top-level constants (classes and modules defined at the top level)
- monkey patches to built-in classes like
StringorArray - global variables (
$foo, and even$VERBOSE) $LOAD_PATHand$LOADED_FEATURES, sorequireis tracked separately per box
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:
- The root box. Ruby boots in it, and all built-in classes are defined and run there.
- The main box. A user box that Ruby creates at the end of startup. Your script, and any files passed with
-r, run in it. - Optional boxes. Each
Ruby::Box.newcreates one. Technically it's the same kind of box as main. - The master box. The template that new boxes are copied from. No code ever runs in it.
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:
box.require_relative "patch"loadspatch.rbinside the box. A box also hasrequire,loadandeval. Any files thatpatch.rbrequires are loaded into the same box too.box::Greeterreaches a constant defined in the box. Inside the box it's justGreeter(or::Greeter). From outside you writebox::Greeter, the same way you'd reach a constant nested in a module.Greeter.greetcallsshoutand it works. Methods defined in a file run in the box that file was loaded into, so they see that box's version ofString.- In the main box,
"x".respond_to?(:shout)isfalse. The monkey patch stays inside the box. Greeterisn't defined at the top level of main, and main's$greetingis stillnil. Top-level constants and globals are per box.box.eval(code)runs a string in the box, as if it were a loaded file. That code sees the patchedStringand the box's$greeting.Ruby::Box.currenttells you which box the running code belongs to.
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:
- Methods added or redefined with
class String ... endare visible only in the box that did it. - A class's instance variables, class variables and constants can also differ per box. If a box sets
Array::V = 1,Array.const_get(:V)raisesNameErrorin the main box. box::String.some_patchdoesn't call the box's patch.box::Stringis justString, so method lookup uses the definitions of the box you're calling from.
Boxes also have side effects you may not expect:
- Built-in methods run in the root box. If you patch
Hash#eachin a box,Hash#map(which callseachinternally) still uses the original. Without boxes, a patch toeachwould changemapas well. - Assigning a global changes it only in your box. Built-in methods that read a global see the root box's value, not yours.
- Top-level methods (
def helperoutside a class) are private methods of that box'sObject, and other boxes have no way to call them. - RubyGems,
error_highlight,did_you_meanandsyntax_suggestare loaded separately in every box, even though they're on by default.
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
box.load_pathis the box's own$LOAD_PATH. Adding to it changed neither the main box's path nor the other box's.- Both boxes have a
Moneymodule, and they're different objects. The main box has noMoneyat all. - Objects created in a box can be used anywhere.
amountis a normalDatainstance whose class came from thenewbox. Calling its methods runs them in that box.
$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:
- The experimental warning appears on every start with
RUBY_BOX=1(-W:no-experimentalhides it). - Installing gems with native extensions may fail under
RUBY_BOX=1(stack level too deepinextconf.rb). require "active_support/core_ext"may fail.- Built-in methods written in Ruby may not see methods defined in a box.
warninside a box doesn't yet use the box's$VERBOSEandWarning.warn.- Boxes don't have their own
TOPLEVEL_BINDINGyet. $LOAD_PATHand$LOADED_FEATURESare taken from the loading box (the one whoserequireyou called), not the box the code runs in. This may change.- C-level method calls (
rb_funcall) get slower when boxes are enabled, because the method cache key includes the current box.
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.