20

I have problems to check syntax of ruby scripts that has rails script/runner on its shebang.

Here are two example scripts and how they responses to ruby syntax checking:

Script hello_world_runner.rb:

#!/usr/bin/env script/runner
p "Hello world!"

Script hello_world.rb

#!/usr/bin/env ruby
p "Hello world!"

Here is how I try to check the syntax. First line is a command and a second line is an output.

$ ruby -c hello_world_runner.rb 
"Hello world!"

$ ruby -c hello_world.rb 
SYNTAX OK
kenorb
  • 155,785
  • 88
  • 678
  • 743
Joni
  • 3,327
  • 3
  • 25
  • 22

5 Answers5

14

You can try this

tail -n +2 hellow_world_runner.rb | ruby -c

Not ideal but should work.

mb14
  • 22,276
  • 7
  • 60
  • 102
7

The ruby command line has these 2 flags that might assist you, I use:

ruby -wc test.rb
kenorb
  • 155,785
  • 88
  • 678
  • 743
Eran Chetzroni
  • 1,046
  • 2
  • 14
  • 27
7

You can rewrite your script like this:

Rails 2:

#!/usr/bin/env ruby
require File.expand_path(Dir.pwd + '/config/boot',  __FILE__)
require RAILS_ROOT + '/config/environment'
p "Hello world!"

Rails 3:

#!/usr/bin/env ruby
require File.expand_path(Dir.pwd + '/config/boot',  __FILE__)
require File.expand_path(Dir.pwd + '/config/application',  __FILE__)
Rails.application.require_environment!
p "Hello world!"

Of course, you need to define your own (absolute) paths or run this script from Rails root.

$ ruby -c ./test.rb 
Syntax OK
Oleksandr Skrypnyk
  • 2,762
  • 1
  • 20
  • 25
3

I would highly recommend that you factor the majority of the code in those scripts into your core domain models/lib directory/etc. This will allow you to test the script logic the same way you test the rest of your application (which will also end up checking syntax) and reduce the actual content of your executable file to a line or two.

Eonflare
  • 66
  • 2
2

Here is a little cheat:

$ ruby -wc <(cat <(echo ruby) hello_world_runner.rb)
Syntax OK

Basically ruby syntax checker expect the ruby word in the first line (shebang).

kenorb
  • 155,785
  • 88
  • 678
  • 743