Class: SafeRuby

Inherits:
Object
  • Object
show all
Defined in:
lib/safe_ruby.rb,
lib/safe_ruby_runner.rb

Constant Summary collapse

VERSION =
"1.0.0"
DEFAULTS =
{ timeout: 5 }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code, options = {}) ⇒ SafeRuby

Returns a new instance of SafeRuby.



8
9
10
11
12
# File 'lib/safe_ruby_runner.rb', line 8

def initialize(code, options={})
  @code = code
  options = DEFAULTS.merge(options)
  @timeout = options[:timeout]
end

Class Method Details

.check(code, expected) ⇒ Object



43
44
45
# File 'lib/safe_ruby_runner.rb', line 43

def self.check(code, expected)
  eval(code) == eval(expected)
end

.eval(code, options = {}) ⇒ Object



14
15
16
# File 'lib/safe_ruby_runner.rb', line 14

def self.eval(code, options={})
  new(code, options).eval
end

Instance Method Details

#evalObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/safe_ruby_runner.rb', line 18

def eval
  temp = build_tempfile
  read, write = IO.pipe
  ChildProcess.build("ruby", temp.path).tap do |process|
    process.io.stdout = write
    process.io.stderr = write
    process.start
    begin
      process.poll_for_exit(@timeout)
    rescue ChildProcess::TimeoutError => e
      process.stop # tries increasingly harsher methods to kill the process.
      return e
    end
    write.close
    temp.unlink
  end

  data = read.read
  begin
    Marshal.load(data)
  rescue => e
    raise data
  end
end