capturing warnings

C

Chris Pine

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top