Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking only syntax of string to be evaled, not evaluate in Ruby

Tags:

string

ruby

eval

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?

like image 353
xis Avatar asked Mar 23 '23 11:03

xis


1 Answers

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
like image 198
sawa Avatar answered Apr 06 '23 23:04

sawa