要使用Ruby显示警告,可以使用标记ruby
调用-w
。使用库时,Ruby可能会显示许多警告,因此很难从您实际处理的文件中找到警告。是否可以告诉ruby
仅显示某些文件的警告?
这是一个说明问题的例子。以下内容加载了一个生成大量警告的库,它还通过重新定义常量来自行生成警告。
require 'grooveshark'
CONSTANT = 'foo'
CONSTANT = 'bar'
ruby -w warning_test.rb
的输出如下:
/var/lib/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/exceptions.rb:157: warning: assigned but unused variable - message /var/lib/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/exceptions.rb:167: warning: assigned but unused variable - message /var/lib/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/response.rb:11: warning: method redefined; discarding old body /var/lib/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/payload.rb:47: warning: mismatched indentations at 'end' with 'case' at 40 /var/lib/gems/1.9.1/gems/macaddr-1.6.1/lib/macaddr.rb:63: warning: assigned but unused variable - status /var/lib/gems/1.9.1/gems/macaddr-1.6.1/lib/macaddr.rb:63: warning: assigned but unused variable - stderr /var/lib/gems/1.9.1/gems/macaddr-1.6.1/lib/macaddr.rb:56: warning: assigned but unused variable - re /var/lib/gems/1.9.1/gems/macaddr-1.6.1/lib/macaddr.rb:59: warning: assigned but unused variable - null /var/lib/gems/1.9.1/gems/systemu-2.5.2/lib/systemu.rb:126: warning: shadowing outer local variable - cid /var/lib/gems/1.9.1/gems/systemu-2.5.2/lib/systemu.rb:213: warning: shadowing outer local variable - buf /var/lib/gems/1.9.1/gems/systemu-2.5.2/lib/systemu.rb:215: warning: shadowing outer local variable - buf /var/lib/gems/1.9.1/gems/systemu-2.5.2/lib/systemu.rb:208: warning: assigned but unused variable - ignored /var/lib/gems/1.9.1/gems/systemu-2.5.2/lib/systemu.rb:252: warning: shadowing outer local variable - key /var/lib/gems/1.9.1/gems/systemu-2.5.2/lib/systemu.rb:249: warning: assigned but unused variable - ignored /var/lib/gems/1.9.1/gems/grooveshark-0.2.7/lib/grooveshark/user.rb:65: warning: method redefined; discarding old playlists /var/lib/gems/1.9.1/gems/grooveshark-0.2.7/lib/grooveshark/user.rb:93: warning: method redefined; discarding old favorites warning_test.rb:4: warning: already initialized constant CONSTANT
在这种情况下,我只想看到最后一个警告
warning_test.rb:4: warning: already initialized constant CONSTANT
由于其他警告是由库引起的,我无法直接控制它们的警告并不那么有趣。我希望能够告诉Ruby只显示正在运行的项目的警告。
我意识到定义当前可能很棘手。也许仅显示给定文件的警告以及通过require_relative
包含的文件。另一种方法是显示目录结构中与给定文件相近的文件的警告。
答案 0 :(得分:1)
你可以将stderr重定向到stdout然后grep。这是一个例子:
ruby -w warning_test.rb 2>&1 | grep "warning_test"