在 Markdown 文件中编辑 YAML Frontmatter

lyo*_*eta 5 ruby yaml jekyll middleman yaml-front-matter

ruby 中是否有某种方法可以编辑 Markdown 文件顶部的 YAML Frontmatter,例如 Jekyll 和 Middleman 中使用的那些?

就像是:

def update_yaml
  #magic that changes A: 1 to A: 2 in Frontmatter block
end
Run Code Online (Sandbox Code Playgroud)

然后我的降价文件将从

---
A: 1
---
# Title
Words. More words. This is the words part of the file.
Run Code Online (Sandbox Code Playgroud)

---
A: 2
---
# Title
Words. More words. This is the words part of the file.
Run Code Online (Sandbox Code Playgroud)

似乎唯一的选择是解析整个文件,然后重写整个文件,只更改所需的部分,但我希望有更好的方法。

lyo*_*eta 0

Middleman 的一位开发人员实际上在 Twitter 上进行了联系,并提供了 Middleman 特定的但仍然非常慷慨和有用的回复。它在实践中与其他答案类似(截至撰写本文时),但它使用了一些中间人功能。他们的回应(经过编辑以在这种情况下有意义)如下。

\n\n
\n\n

如果您制作脚本或扩展,您可以要求middleman-core/util/data它提供::Middleman::Util::Data.parse

\n\n

这将采用文件名和中间人“源文件”以及分隔符列表(---在前面的内容中使用)并返回 2 个值:前面的数据对象和文件其余部分的字符串内容。

\n\n

然后您可以修改这个 ruby​​ 对象并写入文件。

\n\n

所以,阅读会是这样的:

\n\n
require "middleman-core/util/data\xe2\x80\x9d\n\nresource = app.sitemap.resources.find_resource_by_destination_path(\xe2\x80\x9cwhatever.html\xe2\x80\x9d)\n\nfrontmatter, content = ::Middleman::Util::Data.parse(resource.file_descriptor, app.config[:frontmatter_delims])\n
Run Code Online (Sandbox Code Playgroud)\n\n

并写道:

\n\n
# change frontmatter\n\n::File.write(resource.source_file, %Q{\n---\n#{frontmatter.to_yaml}\n---\n\n#{content}\n})\n
Run Code Online (Sandbox Code Playgroud)\n\n

抱歉,数据解析的东西有点奇怪(需要特殊的文件描述符和配置值),这个东西通常在核心之外使用。

\n