Rails console 'y' helper returns NameError rather than yaml-formatting output

梦想的初衷 提交于 2019-11-28 20:42:19

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

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.

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

I'll also use this chance to plug awesome_print, which does for basically everything what y does for YAML.

For rails 4/ruby 2 you could use just

puts object.to_yaml
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!