sp33k3rph433k sp33k3rph433k - 17 days ago 5
Ruby Question

Writing to YAML file with File.open wraps longer lines

I'm wondering if there's an aspect of

File.open
that I'm missing. I'm trying to write some documentation in YAML and when I append to the file and save it at all, it truncates my lines and breaks my formatting.

Here's what's going on:

generated_file = YAML::load_file("#{Rails.root}/documentation/auto_generated/liquid_drops/#{class_name}.yml")


I get the file I'm working with, then all I do is write to it:

File.open("#{Rails.root}/documentation/auto_generated/liquid_drops/#{class_name}.yml", 'w+') {|f| f.write generated_file.to_yaml }


And it truncates lines like this:

example: "{% for file in object.method.all %} -- this would be the ideal method to iterate over a file's methods"


To this:

example: "{% for file in object.method.all %} -- this would be the ideal method
to iterate over a file's methods"


Here's an example of what generated_file looks like:

{
"class" => "account",
"methods" => [
{
"method_name" => "this_method",
"description" => "Donec sed odio dui. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio odio ma.",
"return_type" => "Array",
"example" => "{% for method in object.methods.all %}"
}
],
"general_notes" => "Most methods can use this instead of that, because this and that both inherit from the right file"
}

Answer

Turns out this was actually answered previously in "why does psych yaml interpreter add line breaks around 80 characters?". I was searching for the wrong thing.

Doing something like

yaml.to_yaml(:options = {:line_width => -1})

keeps the lines from wrapping.

Comments