Sha256: 30779b731f0ab5b8314c0f08c65df153ebd3179b74c2c7b7a7fe0520817ce10b

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module BCDD
  class Process
    module Caller
      class NullContract
        attr_reader :value

        def initialize(value)
          @value = value
        end

        def invalid?
          false
        end
      end

      PrepareInputs = ->(spec, input) do
        spec.each_with_object({}) do |(name, options), result|
          value = input.fetch(name) do
            if options.key?(:default)
              default = options[:default]

              default.is_a?(::Proc) ? default.call : default
            end
          end

          value = options[:normalize].call(value) if options.key?(:normalize)

          result[name] = options.key?(:contract) ? options[:contract][value] : NullContract.new(value)
        end
      end

      def call(**inputs)
        prepared_input = PrepareInputs[self.class.__input__, inputs]

        Result.transitions(name: self.class.name) do
          if self.class.__input_contract__
            invalid_input = prepared_input.select { |_key, value| value.invalid? }

            return Failure(:invalid_input, **invalid_input.transform_values(&:errors)) unless invalid_input.empty?
          end

          super(**prepared_input.transform_values!(&:value))
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bcdd-process-0.2.0 lib/bcdd/process/caller.rb