Front matterをパースできるRubyのライブラリ。

waiting-for-dev/front_matter_parser: Ruby library to parse files or strings with a front matter. It has automatic syntax detection.

---
title: Hello World
category: Greetings
---
Some actual content

というMarkdownがあった場合、

require 'front_matter_parser'
 
parsed = FrontMatterParser::Parser.parse_file('example.md')
parsed.front_matter #=> {'title' => 'Hello World', 'category' => 'Greetings'}
parsed.content #=> 'Some actual content'

とすると、このようにパースすることができる。

parsed['category'] #=> 'Greetings'

とすれば直接項目へアクセスすることもできる。

許容するクラスの指定

FrontMatterParserは内部でPsych.safe_loadを使用しており、デフォルトでは以下のクラスのオブジェクトしか変換しない。

  • TrueClass
  • FalseClass
  • NilClass
  • Numeric
  • String
  • Array
  • Hash

このため、例えばTimeクラスやDateクラスを変換対象にしたい場合、

loader = FrontMatterParser::Loader::Yaml.new(allowlist_classes: [Time, Date])
parsed = FrontMatterParser::Parser.parse_file('example.md, loader: loader)

のようにallowlist_classesを指定する必要がある。