截断 irb (ruby) 中的 #inspect 输出
我想截断 irb 中的 #inspect 输出(大输出必须裁剪为 MAX_LEN)。
目前,我覆盖所有特定对象的 :inspect, :to_s 方法。
还有其他解决方案吗?
- 改变 $stdout ?
- 其他?
I want to truncate #inspect output in irb (a large output must be cropped to MAX_LEN).
Currently, I override :inspect, :to_s methods for all specific objects.
Is there are other solution?
- change $stdout ?
- other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于干净的解决方案,
gem install hirb
。 hirb 分页 irb 的返回值(如果它们太长)。如果你想对 irb 进行猴子补丁:
我不推荐这样做,因为它是一种 hack,并且在需要像 ap 和 hirb 这样的 gem 时就会崩溃。
我建议尝试 ripl,而不是猴子修补 irb,这是一种旨在扩展的 irb 替代方案。
以上作为 ripl 插件将是:
使用此插件,您可以根据需要需要它,或者如果您想始终使用它,则将其添加到 ~/.riplrc 中。
For a clean solution,
gem install hirb
. hirb pages irb's returned values if they get too long.If you want to monkeypatch irb:
I don't recommend this because it's a hack and breaks any time gems like ap and hirb are required.
Instead of monkeypatching irb, I'd recommend trying ripl, an irb alternative that is meant to extended.
The above as a ripl plugin would be:
With this plugin, you could require it as needed or add to your ~/.riplrc if you want to always use it.
你的解决方案很好。
它不涉及黑魔法,这可能会使代码更难以理解且容易出错。
Your solution is good.
It involves no dark magic, which might make the code less understandable and error-prone.
如果你只是在IRB中 - 你可以在irb本身中定义一个monkeypatch,或者加载一个monkeypatches通过“load”检查的文件。通过这种方式,您可以将其保留在核心代码库之外,但您仍然可以获得所需的功能,而无需在您希望检查的每个类中覆盖检查......
If you're just in IRB - you could define a monkeypatch in irb itself and or load a file that monkeypatches inspect via 'load'. This way you keep it out of your core codebase but you still get the functionality you need w/o having to override inspect in every class you wish to inspect....
如果是因为您有嵌套散列或难以破译的内容,请尝试 Awesome_print。您可以通过将以下内容放入 .irbrc 中,使其成为 irb 中的默认输出格式化程序:
这使得具有大量数据的对象在 IRB 中易于破译。
即使您不使用 Awesome_print,您也可以使用相同的技术截断输出,这样您就不必在代码中重写 to_s 。
If it's because you have a nested hash or something that's hard to decipher, try awesome_print. You can make it the default output formatter in irb by placing the following in your .irbrc:
This makes objects with lots of data easy to decipher in IRB.
Even if you don't use awesome_print, you can truncate output using this same technique so you don't have to override to_s in your code.
对于 Rails 3.1.1+,请将下面的代码放在 helpers/irb_helper.rb 中。
如果您想更多地自定义输出,请检查 irb 的源代码: https://github.com/Ruby/Ruby/blob/trunk/lib/irb.rb
For rails 3.1.1+, place the code below in helpers/irb_helper.rb
If you'd like to customize your output more, check irb's source at https://github.com/Ruby/Ruby/blob/trunk/lib/irb.rb
我有时会修改对象本身(通过一个名为
BoringInspect
的模块,我将其包含
到相关类中),以便异常消息也可以管理。I sometimes modify the objects themselves (via a module called
BoringInspect
which Iinclude
into the relevant classes) so that exception messages are also manageable.