Last Updated: February 25, 2016
·
634
· mlen

Calling IO functions when $SAFE == 4 in Ruby

class Sandbox
  @@call = lambda do |this, method, *args|
    this.method(method).call(*args)
  end

  def self.method_added(name)
    super
    return if name == :initialize || @adding
    @adding = true
    alias_method(name.to_s + '_orig', name)
    define_method name do |*args|
      @@call[self, name.to_s + '_orig', *args]
    end
    @adding = false
  end

  def initialize(&block)
    Thread.new do
      $SAFE = 4
      instance_eval(&block)
    end.join
  end

  def p(string)
    puts string
  end
end

Sandbox.new do
  p "hello"
  puts "world"
end

1 Response
Add your response

Great, I was looking for something like this, thanks!

over 1 year ago ·