Monday, September 30, 2013

Check Ruby Syntax Recursively

Using the following is great for checking the Ruby syntax of a single file:

ruby -wc path/to/file.rb

It is also useful to recursively check Ruby syntax. This ignores "Syntax OK":

find . -name "*.rb" -exec ruby -wc {} \; grep -v "Syntax OK"

If you want to ignore all warnings which go to stderr:

find . -name "*.rb" -exec ruby -wc {} \; 2>&1 | grep -v "Syntax OK\|: warning:"

And to ignore warnings selectively, change the ": warning:" part and add more strings as needed, e.g.:

find . -name "*.rb" -exec ruby -wc {} \; 2>&1 | grep -v "Syntax OK\|assigned but unused\|shadowing outer"
But not all files containing purely Ruby code end in '.rb'. Include some common files/extensions:

find . \( -name "*.rb" -o -name "*.jbuilder" -o -name "Gemfile" -o -name "Rakefile" -o -name "Appraisals" \) -exec ruby -wc {} \; 2>&1 | grep -v "Syntax OK\|: warning:"

Then you want to put an alias in your .bashrc/.bash_profile:

alias checkrb='find . \( -name "*.rb" -o -name "*.jbuilder" -o -name "Gemfile" -o -name "Rakefile" -o -name "Appraisals" \) -exec ruby -wc {} \; 2>&1 | grep -v "Syntax OK\|: warning:"'

It's possible that it will have an error won't display the pathname, like:

ruby: no Ruby script found in input (LoadError)

In that case, you can echo the pathname before each:

find . \( -name "*.rb" -o -name "*.jbuilder" -o -name "Gemfile" -o -name "Rakefile" -o -name "Appraisals" \) -exec echo {} \; -exec ruby -wc {} \; 2>&1 | grep -v "Syntax OK\|: warning:"

No comments: