Class: SafeEval

Inherits:
Object show all
Defined in:
lib/safe_eval.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(safe = 3, collect = true) ⇒ SafeEval

Returns a new instance of SafeEval.



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

def initialize(safe=3, collect=true)
  @safe = safe
  @collect = collect
end

Instance Attribute Details

#collectObject

Returns the value of attribute collect.



11
12
13
# File 'lib/safe_eval.rb', line 11

def collect
  @collect
end

#outputObject (readonly)

Returns the value of attribute output.



12
13
14
# File 'lib/safe_eval.rb', line 12

def output
  @output
end

#safeObject

Returns the value of attribute safe.



11
12
13
# File 'lib/safe_eval.rb', line 11

def safe
  @safe
end

Instance Method Details

#run(code_str = '', binding = nil, filename = '(SafeEval)', lineno = 1) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/safe_eval.rb', line 19

def run(code_str='', binding=nil, filename='(SafeEval)', lineno=1)
  binding = yield if block_given?
  lineno -= 1
  @output = nil
  @output = [] if @collect
  result = nil
  code_str.strip!
  return result if code_str.empty?
  rd_result, wr_result = IO.pipe
  open('|-') do |io|
    if io.nil? then # son
      status = 0
      rd_result.close
      set_environment
      begin
        code = "$SAFE = #@safe\n#{code_str}"
        result = eval(code, binding, filename, lineno)
        status = 0 # needed if the user change the status
      rescue Exception => exception
        status = 1
        result = exception
      ensure
        Marshal.dump(result, wr_result)
        wr_result.close
        exit!(status)
      end
    else # father
      wr_result.close
      io.each_line { |l| @output << l.chomp } if @collect
      result = Marshal.load(rd_result)
      rd_result.close
      Process.waitpid(io.pid)
    end
  end
  raise result if $?.exitstatus == 1
  @output = nil unless @collect
  return result
end