As title mentions, I need to let users input some Ruby script code and my script will store them for later call. How can I check the user input syntax without actually evaluating?
def correct_syntax? code
stderr = $stderr
$stderr.reopen(IO::NULL)
RubyVM::InstructionSequence.compile(code)
true
rescue Exception
false
ensure
$stderr.reopen(stderr)
end
correct_syntax?("def foo; end") # => true
correct_syntax?("foo") # => true
correct_syntax?("def foo; en") # => false
correct_syntax?("foo bar") # => false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With