Sha256: 562b0e9c8a5f37d07537f7fc473a73f8f7dc0eeef7db4b88e1def22d05bcb492

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module BCDD::Contract
  class Registry
    include ::Singleton

    OPTIONS = ::Set[
      UNIT = :unit,
      LIST = :list,
      PAIRS = :pairs,
      SCHEMA = :schema
    ].freeze

    attr_reader :store, :names

    def initialize
      @names = {}

      @store = {
        UNIT => {},
        LIST => {},
        PAIRS => {},
        SCHEMA => {}
      }
    end

    Kind = ->(checker) do
      case checker
      when Unit::Checker then UNIT
      when List::Checker then LIST
      when Map::Pairs::Checker then PAIRS
      when Map::Schema::Checker then SCHEMA
      else raise ::ArgumentError, "Unknown checker type: #{checker.inspect}"
      end
    end

    def self.write(name, checker)
      kind = Kind[checker]

      return fetch(name) if instance.names.key?(name)

      instance.names[name] = kind

      instance.store[kind][name] = checker
    end

    def self.fetch(name)
      kind = instance.names[name]

      kind or raise(::ArgumentError, format('%p not registered', name))

      read(kind, name)
    end

    def self.unit(name)
      read(UNIT, name)
    end

    def self.read(kind, name)
      instance.store[kind][name]
    end

    private_class_method :read, :instance
  end

  private_constant :Registry
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bcdd-contract-0.1.0 lib/bcdd/contract/registry.rb