20

我在检查其 shebang 上有 rails 脚本/运行器的 ruby​​ 脚本的语法时遇到问题。

以下是两个示例脚本以及它们如何响应 ruby​​ 语法检查:

脚本hello_world_runner.rb

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

脚本hello_world.rb

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

这是我尝试检查语法的方法。第一行是命令,第二行是输出。

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

$ ruby -c hello_world.rb 
SYNTAX OK
4

5 回答 5

14

你可以试试这个

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

不理想,但应该工作。

于 2011-11-08T11:20:31.510 回答
7

ruby 命令行有这两个标志可以帮助你,我使用:

ruby -wc test.rb
于 2014-06-19T09:27:57.080 回答
6

你可以像这样重写你的脚本:

导轨 2:

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

导轨 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!"

当然,您需要定义自己的(绝对)路径或从 Rails 根目录运行此脚本。

$ ruby -c ./test.rb 
Syntax OK
于 2011-09-12T13:38:42.023 回答
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.

于 2011-12-07T18:14:12.560 回答
2

这是一个小骗子:

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

基本上ruby语法检查器期望ruby第一行中的单词(shebang)。

于 2016-06-10T18:10:42.463 回答