Sha256: 26d9f467ed4fc3bf19bb41a992bde57ab85de6546ede63afbc0507d32940142e

Contents?: true

Size: 1.45 KB

Versions: 4

Compression:

Stored size: 1.45 KB

Contents

module Dry
  module Types
    class Array < Definition
      class Member < Array
        # @return [Type]
        attr_reader :member

        # @param [Class] primitive
        # @param [Hash] options
        # @option options [Type] :member
        def initialize(primitive, options = {})
          @member = options.fetch(:member)
          super
        end

        # @param [Object] input
        # @param [Symbol] meth
        # @return [Array]
        def call(input, meth = :call)
          input.map { |el| member.__send__(meth, el) }
        end
        alias_method :[], :call

        # @param [Array, #all?, Object] value
        # @return [Boolean]
        def valid?(value)
          super && value.all? { |el| member.valid?(el) }
        end

        # @param [Array, Object] input
        # @param [#call,nil] block
        # @yieldparam [Failure] failure
        # @yieldreturn [Result]
        # @return [Result,Logic::Result]
        def try(input, &block)
          if input.is_a?(::Array)
            result = call(input, :try)
            output = result.map(&:input)

            if result.all?(&:success?)
              success(output)
            else
              failure = failure(output, result.select(&:failure?))
              block ? yield(failure) : failure
            end
          else
            failure = failure(input, "#{input} is not an array")
            block ? yield(failure) : failure
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dry-types-0.10.3 lib/dry/types/array/member.rb
dry-types-0.10.2 lib/dry/types/array/member.rb
dry-types-0.10.1 lib/dry/types/array/member.rb
dry-types-0.10.0 lib/dry/types/array/member.rb