Sha256: 534188b485622774f23a579a19ba0cf33fdcd60fd0db34d0ca4477e286b87cdc

Contents?: true

Size: 1.58 KB

Versions: 3

Compression:

Stored size: 1.58 KB

Contents

# Author::    Nicolas Despres  <nicolas.despres@gmail.com>.
# Copyright:: Copyright (c) 2004, 2005 TTK team. All rights reserved.
# License::   LGPL
# $Id: SafeEval.rb 567 2005-04-13 08:00:06Z polrop $


class SafeEval

  attr_accessor :collect, :safe
  attr_reader   :output

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

  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
  public :run

  # Can be overloaded to specify environment restriction.
  def set_environment
  end
  protected :set_environment

end # class SafeEval


Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ttk-0.1.576 lib/ttk/Tools/SafeEval.rb
ttk-0.1.579 lib/ttk/Tools/SafeEval.rb
ttk-0.1.580 lib/ttk/Tools/SafeEval.rb