Dynamic syntax check

A

aemadrid

Is there any way to check the Ruby syntax on a file or string of Ruby
code besides doing something like `ruby -v xyz.rb`? Is there a gem
that would help me here?

Thanks in advance,


Adrian Madrid
 
S

Sean O'Halpin

Is there any way to check the Ruby syntax on a file or string of Ruby
code besides doing something like `ruby -v xyz.rb`? Is there a gem
that would help me here?

Thanks in advance,


Adrian Madrid

This should give you a starting point:

def eval_with_check(str, b = binding)
begin
eval(str, b)
"OK"
rescue SyntaxError => e
"ERROR: #{e}"
end
end

puts eval_with_check("1+2")
puts eval_with_check("this is not valid")
puts eval_with_check("RUBY_VERSION")


You could also look into LoadError and other runtime exceptions (don't
remember off the top of my head).

Regards,
Sean
 
R

Ryan Davis

Is there any way to check the Ruby syntax on a file or string of Ruby
code besides doing something like `ruby -v xyz.rb`? Is there a gem
that would help me here?

In emacs you can set up flymake to do syntax checks when idle... but
all it is doing is a `ruby -v tmp$$.rb` on the current buffer contents.
 
C

Calamitas

Is there any way to check the Ruby syntax on a file or string of Ruby
code besides doing something like `ruby -v xyz.rb`? Is there a gem
that would help me here?

From the file sample/test.rb in the Ruby source code distribution:

def valid_syntax?(code, fname)
eval("BEGIN {return true}\n#{code}", nil, fname, 0)
rescue Exception
puts $!.message
false
end

Peter
 
A

aemadrid

This looks really good. Thanks!

AEM

From the file sample/test.rb in the Ruby source code distribution:

def valid_syntax?(code, fname)
eval("BEGIN {return true}\n#{code}", nil, fname, 0)
rescue Exception
puts $!.message
false
end

Peter
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top