Edit YAML Frontmatter in markdown file

Is there any way in ruby ​​to edit YAML Frontmatter at the top of the markdown file, like in Jekyll and Middleman?

Sort of:

def update_yaml
  #magic that changes A: 1 to A: 2 in Frontmatter block
end

Then my markdown file, which would change from

---
A: 1
---
# Title
Words. More words. This is the words part of the file.

to

---
A: 2
---
# Title
Words. More words. This is the words part of the file.

It seems that the only option is to parse the whole file and then rewrite the whole file with only the desired part changed, but I hope there is something better.

+4
source share
4 answers

Middleman Middleman , - . ( ), Middleman. (, ) .


script , middleman-core/util/data, ::Middleman::Util::Data.parse

Middleman (---, ) 2 : .

ruby ​​ .

, :

require "middleman-core/util/data"

resource = app.sitemap.resources.find_resource_by_destination_path("whatever.html")

frontmatter, content = ::Middleman::Util::Data.parse(resource.file_descriptor, app.config[:frontmatter_delims])

:

# change frontmatter

::File.write(resource.source_file, %Q{
---
#{frontmatter.to_yaml}
---

#{content}
})

, ( ), .

0

, , YAML (---), YAML, ( , , ), .

, , , YAML , , YAML " ".

+2

, , python-frontmatter. . yaml:

    import frontmatter
    import io
    with io.open('File.md', 'r') as f:
        post = frontmatter.load(f)
        post['A'] = 2

        # Save the file.
        newfile = io.open(fname, 'w', encoding='utf8')
        frontmatter.dump(post, newfile)
        newfile.close()

+2

, :

require "yaml"

YAML_FRONT_MATTER_REGEXP = /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m

def update_data(data)
  data.merge("A" => 2)
end

if $stdin.read =~ YAML_FRONT_MATTER_REGEXP
  data, content = YAML.load($1), Regexp.last_match.post_match
  data = update_data(data)
  YAML.dump(data, $stdout)
  $stdout.puts("---", content)
end

$stdin $stdout (. Ideone), , Tempfile, Tempfile (, , FileUtils).

, YAML_FRONT_MATTER_REGEXP Jekyll frontmatter.

+1

All Articles