summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/yaml_front_matter_filter.rb
blob: e4e2f3f228dfb65cee613f7858a42def9b5db9bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
require 'html/pipeline/filter'
require 'yaml'

module Banzai
  module Filter
    class YamlFrontMatterFilter < HTML::Pipeline::Filter
      DELIM = '---'.freeze

      # Hat-tip to Middleman: https://git.io/v2e0z
      PATTERN = %r{
        \A(?:[^\r\n]*coding:[^\r\n]*\r?\n)?
        (?<start>#{DELIM})[ ]*\r?\n
        (?<frontmatter>.*?)[ ]*\r?\n?
        ^(?<stop>#{DELIM})[ ]*\r?\n?
        \r?\n?
        (?<content>.*)
      }mx.freeze

      def call
        match = PATTERN.match(html)

        return html unless match

        "```yaml\n#{match['frontmatter']}\n```\n\n#{match['content']}"
      end
    end
  end
end