Sha256: 5076ec3f8b7f604d955d857f0456b8c574088fff2db551d254c11092881b452b

Contents?: true

Size: 1.81 KB

Versions: 7

Compression:

Stored size: 1.81 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).reject { |r| r.input.equal?(Undefined) }
            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

        # @api public
        #
        # @see Definition#to_ast
        def to_ast(meta: true)
          if member.respond_to?(:to_ast)
            [:array, [member.to_ast(meta: meta), meta ? self.meta : EMPTY_HASH]]
          else
            [:array, [member, meta ? self.meta : EMPTY_HASH]]
          end
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
dry-types-0.14.1 lib/dry/types/array/member.rb
dry-types-0.14.0 lib/dry/types/array/member.rb
dry-types-0.13.4 lib/dry/types/array/member.rb
dry-types-0.13.3 lib/dry/types/array/member.rb
dry-types-0.13.2 lib/dry/types/array/member.rb
dry-types-0.13.1 lib/dry/types/array/member.rb
dry-types-0.13.0 lib/dry/types/array/member.rb