Sha256: 87479e32ad630ecdab3ce03c80e94f153067a04f542959d5adcec0fc78acba68

Contents?: true

Size: 1.97 KB

Versions: 7

Compression:

Stored size: 1.97 KB

Contents

# frozen_string_literal: true

module Scribo
  class Preamble
    DEFAULTS = {
      external_encoding: Encoding.default_external
    }.freeze

    attr_accessor :metadata, :content

    def initialize(metadata, content)
      @metadata = metadata
      @content  = content
    end

    def metadata_with_content
      @metadata.to_yaml + "---\n" + @content
    end

    def dump
      metadata_with_content
    end

    def save(path, options = {})
      options = DEFAULTS.merge(options)

      File.open(path, "w:#{options[:external_encoding]}") do |f|
        f.write metadata_with_content
      end
    end

    def self.parse(data)
      preamble_lines = +''
      content_lines  = +''

      state = :before_preamble

      f = StringIO.new(data)
      f.each do |line|
        stripped = line.strip

        case state
        when :before_preamble

          new_state = case stripped
                      when '---'
                        :preamble
                      when ''
                        :before_preamble
                      else
                        content_lines << line
                        :after_preamble
                      end

        when :preamble

          new_state = case stripped
                      when '---'
                        :after_preamble
                      else
                        preamble_lines << line
                        :preamble
                      end

        when :after_preamble
          new_state = :after_preamble
          content_lines << line

        else
          raise "Invalid State: #{state}"
        end

        state = new_state
      end

      new(Scribo::Utility.yaml_safe_parse(preamble_lines), content_lines)
    end

    def self.load(path, options = {})
      f = File.open(path, "r:#{options[:external_encoding]}")
      parse(f.read)
    end

    def self.load_multiple(*paths)
      options = paths.last.is_a?(Hash) ? paths.pop : {}
      paths.map { |path| Preamble.load(path, options) }
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
scribo-1.0.44 lib/scribo/preamble.rb
scribo-1.0.43 lib/scribo/preamble.rb
scribo-1.0.42 lib/scribo/preamble.rb
scribo-1.0.41 lib/scribo/preamble.rb
scribo-1.0.40 lib/scribo/preamble.rb
scribo-1.0.39 lib/scribo/preamble.rb
scribo-1.0.38 lib/scribo/preamble.rb