6

According to the YAML documentation it's possible to pass a hash of options to the .to_yaml method.

Currently when I pass the options as suggested by the documentation it's not working, the hash is being ignored.

irb(main):001:0> require 'yaml'
=> true
irb(main):002:0> user = { "1" => { "name" => "john", "age" => 44 } }
user.to_yaml
=> "--- \n\"1\": \n  name: john\n  age: 44\n"

Now, passing some options:

irb(main):014:0> user.to_yaml( :Indent => 4, :UseHeader => true, :UseVersion => true )
=> "--- \n\"1\": \n  name: john\n  age: 44\n"
irb(main):015:0> user.to_yaml( :Separator => "\n" )
=> "--- \n\"1\": \n  name: john\n  age: 44\n"
irb(main):016:0> user.to_yaml( :separator => "\n" )
=> "--- \n\"1\": \n  name: john\n  age: 44\n"
irb(main):017:0> RUBY_VERSION
=> "1.9.1"

As you can see, passing the options don't work. Only the defaults:

YAML::DEFAULTS
=> {:Indent=>2, :UseHeader=>false, :UseVersion=>false, :Version=>"1.0", :SortKeys=>false, :AnchorFormat=>"id%03d", :ExplicitTypes=>false, :WidthType=>"absolute", :BestWidth=>80, :UseBlock=>false, :UseFold=>false, :Encoding=>:None}

Is this a known bug? or It's currently working for anyone using Ruby 1.9.1 ?

jpemberthy
  • 7,473
  • 8
  • 44
  • 52
  • I get the same behavior as you are seeing. It looks as if this has been asked before without resolution: http://stackoverflow.com/questions/1054730/is-it-possible-to-specify-formatting-options-for-toyaml-in-ruby – Mark Wilkins Jan 28 '10 at 18:57
  • Yes, in that case they were using 1.8.7, I was just wondering if it works for 1.9.1, it seems to be a problem without a concise answer. – jpemberthy Jan 28 '10 at 19:09
  • I'd love to know the answer to this one. I long ago gave up and wrote my own "sort the yaml" function (for 1.8.7). – Wayne Conrad Jan 28 '10 at 19:22
  • Is 1.9.1 using the same presumably abandoned _why YAML writer as 1.8.x? I've had nothing but trouble with it when trying to send options and customize it. – tadman Jan 28 '10 at 21:16
  • @tadman, From looking at the source, I'd say "yes" for 1.8.7, 1.9.0 and 1.9.1. – Wayne Conrad Jan 28 '10 at 21:50
  • I had so much trouble with it trying to serialize HAML HTML that I gave up and switched to JSON. Sadly it's quite buggy around the edges. – tadman Jan 28 '10 at 22:25

1 Answers1

2

I have dug relatively deep into the C source for this in the not so distant past. I'm posting just to validate what's already been said in the comments.

Basically, can't do it. The Syck options get lost somewhere in the process, before ever hitting the YAML writer.

The best you can have is to_yaml_style. Sometimes.

This is the same for 1.8 and 1.9.

kch
  • 77,385
  • 46
  • 136
  • 148
  • Ok, well I ended writing a small module to get it formatted, not as optimal as it should be using the `to_yaml` method ... but at least it works. Thanks. – jpemberthy Mar 11 '10 at 19:39