Reputation: 311
I use following now to check syntax error:
system "ruby -wc path/to/file.rb"
but it very waste time if there are too many file(for instance, i refactory code), so my question is: is there way to ruby syntax check in ruby code?
Upvotes: 17
Views: 15333
Reputation: 16222
The simplest way is with the command line -c
flag:
ruby -c file_you_want_to_check.rb
Upvotes: 4
Reputation: 87416
You can use Ripper, the Ruby interface to the Ruby parser:
http://ruby-doc.org/stdlib/libdoc/ripper/rdoc/Ripper.html
Upvotes: 0
Reputation: 62648
Under MRI, you can use RubyVM::InstructionSequence#compile
(relevant documentation) to compile Ruby code (which will throw exceptions if there are errors):
2.1.0 :001 > RubyVM::InstructionSequence.compile "a = 1 + 2"
=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
2.1.0 :002 > RubyVM::InstructionSequence.compile "a = 1 + "
<compiled>:1: syntax error, unexpected end-of-input
a = 1 +
^
SyntaxError: compile error
from (irb):2:in `compile'
from (irb):2
from /usr/local/rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'
Upvotes: 8
Reputation: 697
My experience has been that the easiest way to check whether my code is properly compiled is to run automated tests. The compiler is going to do the same work whether it's compiling to run tests or just checking that files are lexically correct.
MRI's parser is written in C. I couldn't find a specific reference to how to access it, though I'm sure there's a way to do that. If only someone had spent some time making Ruby more Ruby-aware...
In Rubinius, there is direct access to the parser via Melbourne:
rbx-2.2.10 :039 > Rubinius::ToolSets::Runtime::Melbourne.parse_file("./todo.txt")
SyntaxError: expecting keyword_do or '{' or '(': ./todo.txt:2:17
and for a valid ruby file:
rbx-2.2.10 :044 > Rubinius::ToolSets::Runtime::Melbourne.parse_file('./valid.rb')
=> #<Rubinius::ToolSets::Runtime::AST::Class:0x1e6b4 @name=# <Rubinius::ToolSets::Runtime::AST::ClassName:0x1e6b8 @name=:RubyStuff @line=1 @superclass=#<Rubinius::ToolSets::Runtime::AST::NilLiteral:0x1e6bc @line=1>> @body=#<Rubinius::ToolSets::Runtime::AST::EmptyBody:0x1e6c8 @line=1> @line=1 @superclass=#<Rubinius::ToolSets::Runtime::AST::NilLiteral:0x1e6bc @line=1>>
You're currently using command-line tools to parse ruby. If you're doing some looping through files in Ruby, maybe you should just take that to the command-line as well and do something like:
jw@logopolis:/projects/open/compile-test$ find . | grep ".rb$" | xargs ruby -c
Syntax OK
jw@logopolis:/projects/open/compile-test$ find . | grep ".rb$" | xargs ruby -c
./invalid.rb:2: expecting $end: ./invalid.rb:2:3
which looks like this in Ruby:
system "find . | grep ".rb$" | xargs ruby -c"
http://rubini.us/doc/en/bytecode-compiler/parser/
Upvotes: 5