Sha256: eec2c81c4771b19d431d6b1a67d02dd27d7bb1f4056ee7581a57692f0e57f070

Contents?: true

Size: 1.82 KB

Versions: 34

Compression:

Stored size: 1.82 KB

Contents

module Foobara
  class DomainMapper
    class NoDomainMapperFoundError < StandardError
      attr_accessor :value, :from, :to, :has_value

      def initialize(from, to, **opts)
        valid_keys = [:value]
        invalid_keys = opts.keys - [:value]

        if invalid_keys.any?
          # :nocov:
          raise ArgumentError, "Invalid keys: #{invalid_keys.join(", ")}. expected one of: #{valid_keys.join(", ")}"
          # :nocov:
        end

        if opts.key?(:value)
          self.has_value = true
          self.value = opts[:value]
        end

        self.from = from
        self.to = to

        super("No domain mapper found for #{value}. from: #{from}. to: #{to}.")
      end
    end

    class Registry
      class AmbiguousDomainMapperError < StandardError
        attr_accessor :candidates, :from, :to

        def initialize(from, to, candidates)
          self.to = to
          self.from = from
          self.candidates = [*candidates].flatten

          super("#{candidates.size} ambiguous candidates found.")
        end
      end

      def register(mapper)
        mappers << mapper
      end

      def lookup!(from: nil, to: nil, strict: false)
        result = lookup(from:, to:, strict:)

        result || raise(NoDomainMapperFoundError.new(from, to))
      end

      def lookup(from: nil, to: nil, strict: false)
        candidates = mappers.select do |mapper|
          mapper.applicable?(from, to)
        end

        if candidates.size > 1
          raise AmbiguousDomainMapperError.new(from, to, candidates)
        end

        value = candidates.first

        return value if value

        unless strict
          if from
            lookup(from: nil, to:)
          elsif to
            lookup(from:, to: nil)
          end
        end
      end

      def mappers
        @mappers ||= []
      end
    end
  end
end

Version data entries

34 entries across 34 versions & 1 rubygems

Version Path
foobara-0.0.16 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.15 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.14 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.13 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.12 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.11 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.10 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.9 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.8 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.7 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.6 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.5 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.4 projects/domain/src/domain_mapper/registry.rb
foobara-0.0.3 projects/domain/src/domain_mapper/registry.rb