Ruby and eRuby Syntax Validation

Ruby

require "open3" 

def check_ruby_syntax(code)
  Open3.popen3("ruby -c") do |stdin, stdout, stderr|
    stdin.write(code)
    stdin.close

    errors = stderr.read
  end

  return errors.empty? ? :ok : errors
end

def valid_ruby_syntax?(code)
  check_ruby_syntax(code) == :ok
end

Demo

check_ruby_syntax("f+)4ff")
# => "-:1: syntax error, unexpected ')'\nf+)4ff\n   ^\n" 

valid_ruby_syntax? "foo = bar" # => true

eRuby

require "erb" 

def check_eruby_syntax(code)
  check_ruby_syntax(ERB.new(code).src)
end

def valid_eruby_syntax?(code)
  check_eruby_syntax(code) == :ok
end