Sha256: 093b2f6fa4c68e4203cd2ad1417f7d60fc31f97ab7b91480910e569f3d928989

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

module Munge
  module Core
    class ItemFactory
      class ContentParser
        def self.match(string)
          string.match(/
            # Start of string
            \A
            # Begin frontmatter
            (?:^---\s*[\n\r]+)
            # Capture frontmatter
            (.*)
            # End frontmatter
            (?:^---\s*[\n\r]+)
            /mx)
        end

        def self.parse(string)
          matchdata = match(string)

          [
            parse_frontmatter(matchdata),
            parse_content(matchdata, string)
          ]
        end

        def self.parse_frontmatter(matchdata)
          return {} if matchdata.nil?

          parsed_frontmatter = YAML.load(matchdata[1])

          if parsed_frontmatter
            parsed_frontmatter
          else
            {}
          end
        end

        def self.parse_content(matchdata, string)
          if matchdata
            matchdata.post_match
          else
            string
          end
        end

        def initialize(string, frontmatter = nil)
          @frontmatter, @content = self.class.parse(string)

          if frontmatter
            @frontmatter = @frontmatter.merge(frontmatter)
          end
        rescue ArgumentError
          @frontmatter = frontmatter || {}
          @content     = string
        end

        attr_accessor :frontmatter, :content
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
munge-0.4.0 lib/munge/core/item_factory/content_parser.rb