How to check syntax of ruby script that has script/runner as a shebang?
Asked Answered
O

5

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
Occiput answered 12/9, 2011 at 6:46 Comment(0)
T
14

You can try this

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

Not ideal but should work.

Trave answered 8/11, 2011 at 11:20 Comment(0)
D
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
Dottydoty answered 12/9, 2011 at 13:38 Comment(0)
S
7

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

ruby -wc test.rb
Sundog answered 19/6, 2014 at 9:27 Comment(0)
C
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.

Closelipped answered 7/12, 2011 at 18:14 Comment(0)
L
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).

Luddite answered 10/6, 2016 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.