Created
January 6, 2026 22:15
-
-
Save havenwood/e088d42aed27bc3ab0d4be27b8930733 to your computer and use it in GitHub Desktop.
An example just to demonstrate how the new `Ruby::Box` sandboxes stuff including globals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'optparse' | |
| class Options < Ruby::Box | |
| class Into | |
| class BadKeyError < ArgumentError | |
| def initialize(key) = super("Bad key: #{key.inspect}") | |
| end | |
| def []=(key, value) | |
| global = "$#{key.to_s.delete_prefix('$').tr('-', '_')}" | |
| raise BadKeyError, global unless global.match?(/\A\$[[:alpha:]_][[:alnum:]_]*\z/) | |
| eval("#{global} = value", binding, __FILE__, __LINE__) | |
| end | |
| end | |
| def initialize(argv = ARGV, &block) | |
| super() | |
| parser = OptionParser.new | |
| block&.call(parser) | |
| parser.parse!(argv, into: Into.new) | |
| end | |
| def [](name) | |
| global = "$#{name.to_s.delete_prefix('$')}" | |
| Kernel.eval(global, binding, __FILE__, __LINE__) | |
| end | |
| end | |
| options = Options.new do |parser| | |
| parser.on '--warn' | |
| end | |
| warn 'oops' if options[ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment