Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force double-quotes when dumping YAML?

Tags:

ruby

yaml

I have a small script to automate some things in YAML files.

I read the original YAML file and convert it into a hash and then dump it to the file after modifying it:

File.open(output_file, "w") do |out|
  YAML.dump(modified_hash, out)
end

That works fine, but it removes double-quotes around the string if they aren't needed. That's valid YAML, but it doesn't look very nice.

I could add a space at the end of every string to force single-quotes, but I'm not too happy with that. Is there any way of forcing double-quotes around strings?

like image 838
jomo Avatar asked Aug 19 '13 14:08

jomo


1 Answers

This works pretty well. I got it from here

require 'psych'

ast = Psych.parse_stream DATA.read

# First pass, quote everything
ast.grep(Psych::Nodes::Scalar).each do |node|
  node.plain  = false
  node.quoted = true
  node.style  = Psych::Nodes::Scalar::DOUBLE_QUOTED
end

# Second pass, unquote keys
ast.grep(Psych::Nodes::Mapping).each do |node|
  node.children.each_slice(2) do |k, _|
    k.plain  = true
    k.quoted = false
    k.style  = Psych::Nodes::Scalar::ANY
  end
end

puts ast.yaml
like image 133
Kyle Heironimus Avatar answered Sep 22 '22 20:09

Kyle Heironimus