Rails控制台"y"助手返回NameError而不是yaml格式的输出 [英] Rails console 'y' helper returns NameError rather than yaml-formatting output
问题描述
我试图在Rails 3.2.6/Ruby 1.9.3控制台中使用y object
为ActiveRecord对象获取格式正确的yaml输出,但是由于某些原因,它对我不起作用.我过去曾使用过它,但是在它坏掉的过程中一直使用它.我尝试时会得到以下输出:
I'm trying to use y object
in Rails 3.2.6/Ruby 1.9.3 console to get nicely formatted yaml output for an ActiveRecord object, but for some reason it isn't working for me. I've used it in the past, but somewhere along the way it broke. I get the following output when I try:
NameError: undefined local variable or method `yaml' for main:Object
推荐答案
y
方法实际上是对Syck YAML解析器/发射器.这是lib/ruby/1.9.1/syck.rb
的最后几行:
The y
method is actually an extension to the Kernel
object put in place by the Syck YAML parser/emitter. Here are the last few lines of lib/ruby/1.9.1/syck.rb
:
module Kernel
def y( object, *objects )
objects.unshift object
puts( if objects.length == 1
YAML.dump( *objects )
else
YAML.dump_stream( *objects )
end )
end
private :y
end
默认情况下,Ruby 1.9.3使用心理分析器/发射器代替Syck(我只能假定它们是发音不同),而Psych则没有声明这种方法.
By default, Ruby 1.9.3 uses the Psych parser/emitter instead of Syck (I can only presume they're pronounced differently), and Psych doesn't declare such a method.
如果您真的喜欢y
,则只需在控制台中使用Syck而不是Psych:
If you really loved y
, you can simply use Syck instead of Psych in the console:
Loading development environment (Rails 3.2.5)
1.9.3p194 :001 > y 'hello'
NoMethodError: undefined method 'y' for main:Object
1.9.3p194 :002 > YAML::ENGINE.yamler = 'syck'
"syck"
1.9.3p194 :003 > y 'hello'
--- hello
nil
我还将利用这次机会插入 awesome_print ,它基本上可以完成y
对YAML所做的一切.
I'll also use this chance to plug awesome_print, which does for basically everything what y
does for YAML.
这篇关于Rails控制台"y"助手返回NameError而不是yaml格式的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!