Sha256: 461726291180023c81f3533abb0b593f5c19bf93a883408b4b19beb154e96369

Contents?: true

Size: 1.29 KB

Versions: 4

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

module Bridgetown
  module Utils
    module RubyFrontMatterDSL
      def front_matter(scope: nil, &block)
        RubyFrontMatter.new(scope: scope).tap { |fm| fm.instance_exec(&block) }
      end
    end

    class RubyFrontMatter
      def initialize(scope: nil, data: {})
        @data, @scope = data, scope
      end

      def method_missing(key, *value, &block) # rubocop:disable Metrics/CyclomaticComplexity, Style/MissingRespondToMissing
        return super if respond_to?(key) || (value.length.zero? && block.nil? && !@data.key?(key))

        return get(key) if value.length.zero? && block.nil? && @data.key?(key)

        set(key, value[0], &block)
      end

      def each(&block)
        @data.each(&block)
      end

      def get(key)
        @data[key]
      end

      def set(key, value = nil, &block)
        # Handle nested data within a block
        if block
          value = self.class.new(scope: @scope).tap do |fm|
            fm.instance_exec(&block)
          end.to_h
        end

        # Execute lambda value within the resolver
        if @scope && value.is_a?(Hash) && value[:from].is_a?(Proc)
          value = @scope.instance_exec(&value[:from])
        end

        @data[key] = value
      end

      def to_h
        @data
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
bridgetown-core-1.2.0.beta4 lib/bridgetown-core/utils/ruby_front_matter.rb
bridgetown-core-1.2.0.beta3 lib/bridgetown-core/utils/ruby_front_matter.rb
bridgetown-core-1.2.0.beta2 lib/bridgetown-core/utils/ruby_front_matter.rb
bridgetown-core-1.2.0.beta1 lib/bridgetown-core/utils/ruby_front_matter.rb