Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}
like image 491
camkidman Avatar asked Oct 21 '25 15:10

camkidman


2 Answers

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.

like image 144
camkidman Avatar answered Oct 24 '25 06:10

camkidman


I would not call that truncating, but wrapping with indent, a decades old technique for lines that are too long e.g. for a terminal width.

In .to_yaml this width is determined by the BestWidth parameter and defaults to 80 characters. More options can be found on the documentation page under section 24.

YAML emittors for other programming languages use this wrapping as well.

like image 30
Anthon Avatar answered Oct 24 '25 07:10

Anthon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!