Sha256: e9239e026c27b9cf54f76342dc6c2a0b8e51d2125e5ef2abddfcfc74d7c30e99

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 KB

Contents

# frozen_string_literal: true

require_relative "container/mixin"

module FunRuby
  # @private
  class Container
    NAMESPACE_SEPARATOR = "."
    NOT_EVALUATED = Object.new.freeze

    # @private
    def initialize
      @storage = {}
      @mutex = Mutex.new
    end

    # @private
    def define(key, &block)
      key = key.to_s

      raise KeyError, "#{key.inspect} is already defined" if storage.key?(key)
      raise TypeError, "block should be given" unless block_given?

      storage[key] = init_meta(block)
    end

    # @private
    def fetch(key)
      key = key.to_s
      meta = storage.fetch(key)
      value = storage[key].fetch(:value)
      return value unless value.equal?(NOT_EVALUATED)

      meta.fetch(:definition).().tap do |evaluated|
        storage[key][:value] = evaluated
      end
    end

    # @private
    def import(*aliases)
      Mixin.build(aliases: aliases)
    end

    private

    attr_reader :storage, :mutex

    def init_meta(definition)
      {
        definition: definition,
        value: NOT_EVALUATED
      }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fun-ruby-0.0.1 lib/fun_ruby/container.rb