Hello,
Here’s a method which executes the code in the string code', giving it the input from the array of strings
input’ as it asks for it. The output is
captured, and so are any errors.
However, it doesn’t capture warnings. Anyone know how to do that? NOTE: I
only want to capture warning generated by the code in `code’, not in the
rest of my program.
def executeCode (code, input)
# Wrap code to catch errors and to stop SystemExit.
code = <<-END_CODE
begin
#{code}
rescue SystemExit
rescue Exception => error
puts error.inspect
end
END_CODE
strIO = StringIO.new
if !input.empty?
input = input.join("\n")+"\n"
input = StringIO.new(input, "r")
class << strIO; self; end.module_eval do
['gets', 'getc', 'read'].each do |meth|
define_method(meth) do |*params|
inStr = input.method(meth).call(*params)
puts @@INPUT+inStr.chomp+(@@INPUT.reverse) # Echo input.
inStr
end
end
end
end
# Pass these methods to strIO:
kernelMethods = ['puts', 'putc', 'gets']
# Swap out Kernel methods...
kernelMethods.each do |meth|
Kernel.module_eval "alias __temp__tutorial__#{meth}__ #{meth}"
Kernel.module_eval do
define_method(meth) do |*params|
strIO.method(meth).call(*params)
end
end
end
begin
strIO.instance_eval code
rescue Exception => error # Catch parse errors.
return error.inspect
end
# ...and swap them back in.
kernelMethods.each do |meth|
Kernel.module_eval "alias #{meth} __temp__tutorial__#{meth}__"
end
strIO.string
end
Any help would be much appreciated,
Chris