| Class | SafeEval |
| In: |
lib/safe_eval.rb
|
| Parent: | Object |
$LastChangedBy: pouillar $ $Id: /w/fey/ruby_ex/trunk/lib/safe_eval.rb 21871 2006-02-19T00:36:31.457482Z pouillar $
| collect | [RW] | |
| output | [R] | |
| safe | [RW] |
# File lib/safe_eval.rb, line 14 def initialize(safe=3, collect=true) @safe = safe @collect = collect end
# 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