我在 Rails 控制台的生产服务器中测试了一些数据库条目,其中几乎所有命令都产生大量输出行并导致 ssh 通道挂起。
有没有办法抑制控制台/irb screenfuls?
我在 Rails 控制台的生产服务器中测试了一些数据库条目,其中几乎所有命令都产生大量输出行并导致 ssh 通道挂起。
有没有办法抑制控制台/irb screenfuls?
您可以附加; nil
到您的陈述。
例子:
users = User.all; nil
irb
打印最后执行的语句的返回值;因此在这种情况下,它只会打印,nil
因为nil
它是最后执行的有效语句。
在寻找如何使 irb/console 输出静音的解决方案时,我还在austinruby.com找到了答案:
沉默irb:
conf.return_format = ""
默认输出:
conf.return_format = "=> %s\n"
限制为例如 512 个字符:
conf.return_format = "=> limited output\n %.512s\n"
在这里,将其添加到您的 ~/.irbrc:
require 'ctx'
require 'awesome_print'
module IRB
class Irb
ctx :ap do
def output_value()
ap(@context.last_value)
end
end
ctx :puts do
def output_value()
puts(@context.last_value)
end
end
ctx :p do
def output_value()
p(@context.last_value)
end
end
ctx :quiet do
def output_value()
end
end
end
end
def irb_mode(mode)
ctx(mode) { irb }
end
(注意:您必须先安装ctx
gem,当然这awesome_print
是可选的。)
现在,当您在任何使用 irb 的控制台上时,您可以执行以下操作:
正常模式:
irb(main):001:0> { this:'is a complex object', that:[ { will:'probably'}, { be:'good to read' } ], in:{ some:{ formatted:'way'} } }
=> {:this=>"is a complex object", :that=>[{:will=>"probably"}, {:be=>"good to read"}], :in=>{:some=>{:formatted=>"way"}}}
...是的,正如你所期望的那样。
awesome_print
模式:
irb(main):002:0> irb_mode(:ap)
irb#1(main):001:0> { this:'is a complex object', that:[ { will:'probably'}, { be:'good to read' } ], in:{ some:{ formatted:'way'} } }
=> {
:this => "is a complex object",
:that => [
[0] {
:will => "probably"
},
[1] {
:be => "good to read"
}
],
:in => {
:some => {
:formatted => "way"
}
}
}
...哇,现在一切都打印出来了!:)
静音模式:
irb#1(main):002:0> irb_mode(:quiet)
irb#1(main):001:0> { this:'is a complex object', that:[ { will:'probably'}, { be:'good to read' } ], in:{ some:{ formatted:'way'} } }
irb#1(main):002:0>
...哇,根本没有输出?好的。
无论如何,您可以添加您喜欢的任何模式,当您完成该模式时,只需exit
退出或退出,您将回到以前的模式。
希望这有帮助!:)
irb --simple-prompt --noecho
--simple-prompt
- Uses a simple prompt - just >>
--noecho
- Suppresses the result of operations在 irb 中运行以下内容对我有用:
irb_context.echo = false
此外,根据您的需要,请查看使用quietly
或silence_stream
抑制一般输出,而不仅仅是在 irb/console 中:
silence_stream(STDOUT) do
users = User.all
end
注意:silence_stream
在 Rails 5+ 中删除。
注意:quietly
将在 Ruby 2.2.0 中弃用,最终将被删除。 (感谢BenMorganIO!)
更多信息可以在这里找到。
如上所述,silence_stream
不再可用,因为它不是线程安全的。没有线程安全的替代方案。但是如果您仍然想使用silence_stream
并且知道它不是线程安全的并且没有以多线程方式使用它,您可以手动将其添加回作为初始化程序。
config/initializer/silence_stream.rb
# Re-implementation of `silence_stream` that was removed in Rails 5 due to it not being threadsafe.
# This is not threadsafe either so only use it in single threaded operations.
# See https://api.rubyonrails.org/v4.2.5/classes/Kernel.html#method-i-silence_stream.
#
def silence_stream( stream )
old_stream = stream.dup
stream.reopen( File::NULL )
stream.sync = true
yield
ensure
stream.reopen( old_stream )
old_stream.close
end