-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
member.rb
61 lines (55 loc) · 1.64 KB
/
member.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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)
if result.all?(&:success?)
output = result.map(&:input)
success(output)
else
failure = failure(input, 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)
[:array, [member.to_ast(meta: meta), meta ? self.meta : EMPTY_HASH]]
end
end
end
end
end