Sha256: 93ba39d4f7b951d2a1d5a2407a3e051ac780da7656c6e8fb09f8d85cb60175d6

Contents?: true

Size: 1.26 KB

Versions: 2

Compression:

Stored size: 1.26 KB

Contents

# frozen_string_literal: true

module Dry
  module AutoInject
    DuplicateDependencyError = Class.new(StandardError)
    DependencyNameInvalid = Class.new(StandardError)

    VALID_NAME = /([a-z_][a-zA-Z_0-9]*)$/

    class DependencyMap
      def initialize(*dependencies)
        @map = {}

        dependencies = dependencies.dup
        aliases = dependencies.last.is_a?(Hash) ? dependencies.pop : {}

        dependencies.each do |identifier|
          name = name_for(identifier)
          add_dependency(name, identifier)
        end

        aliases.each do |name, identifier|
          add_dependency(name, identifier)
        end
      end

      def inspect
        @map.inspect
      end

      def names
        @names ||= @map.keys
      end

      def to_h
        @map.dup
      end
      alias_method :to_hash, :to_h

      private

      def name_for(identifier)
        matched = VALID_NAME.match(identifier.to_s)
        raise DependencyNameInvalid, "name +#{identifier}+ is not a valid Ruby identifier" unless matched
        matched[0]
      end

      def add_dependency(name, identifier)
        name = name.to_sym
        raise DuplicateDependencyError, "name +#{name}+ is already used" if @map.key?(name)
        @map[name] = identifier
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-auto_inject-0.7.0 lib/dry/auto_inject/dependency_map.rb
dry-auto_inject-0.6.1 lib/dry/auto_inject/dependency_map.rb