【问题标题】:Writing to YAML file with File.open wraps longer lines使用 File.open 写入 YAML 文件会换行较长的行
【发布时间】:2015-10-07 03:13:01
【问题描述】:

我想知道我是否缺少File.open 的某个方面。我正在尝试用 YAML 编写一些文档,当我附加到文件并完全保存它时,它会截断我的行并破坏我的格式。

这是怎么回事:

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

我得到了我正在使用的文件,然后我所做的就是写入它:

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

它会像这样截断行:

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

到这里:

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

以下是 generate_file 的示例:

{
  "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"
}

【问题讨论】:

  • 我想出了其中的一部分,generated_method.to_yaml 是在那里添加新行的原因。我现在正在调查原因。

标签: ruby-on-rails ruby yaml


【解决方案1】:

我不会称之为截断,而是用缩进包裹,这是一种几十年前的技术,用于太长的行,例如对于终端宽度。

.to_yaml 中,此宽度由BestWidth 参数确定,默认为80 个字符。更多选项可以在documentation page 的第 24 节下找到。

其他编程语言的 YAML 发射器也使用这种包装。

【讨论】:

    【解决方案2】:

    原来这实际上是以前在“why does psych yaml interpreter add line breaks around 80 characters?”中回答的。我在寻找错误的东西。

    做类似的事情

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

    不换行。

    【讨论】:

    • 代码中有错别字。应该是:yaml.to_yaml(:options => {:line_width => -1})yaml.to_yaml(options = {:line_width => -1}) 但“编辑不能更改少于 6 个字符”。 :)
    【解决方案3】:

    很可能是to_yaml 方法添加了换行符。 File.openwrite 方法不应添加换行符。试试

    f.write generated_file
    

    f.write generated_file.to_s
    

    没有to_yaml 方法。

    【讨论】:

    • 我确实将其隔离为该方法,当我将generated_file.to_yaml 输出到控制台时,由于某种奇怪的原因,它会在长行中中断。我可能不得不以不同的方式解决这个问题。
    • 是的,.to_s 没有添加换行符,但我知道它是什么。 YAML 解析器的默认行为是在 80 个字符后添加换行符,但添加 options = {:line_width => -1} 会阻止
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2020-07-15
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多