-
-
Notifications
You must be signed in to change notification settings - Fork 131
/
member.rb
124 lines (109 loc) · 3.05 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# frozen_string_literal: true
require 'dry/types/array/constructor'
module Dry
module Types
class Array < Nominal
# Member arrays define their member type that is applied to each element
#
# @api public
class Member < Array
# @return [Type]
attr_reader :member
# @param [Class] primitive
# @param [Hash] options
#
# @option options [Type] :member
#
# @api private
def initialize(primitive, options = {})
@member = options.fetch(:member)
super
end
# @param [Object] input
#
# @return [Array]
#
# @api private
def call_unsafe(input)
if primitive?(input)
input.each_with_object([]) do |el, output|
coerced = member.call_unsafe(el)
output << coerced unless Undefined.equal?(coerced)
end
else
super
end
end
# @param [Object] input
# @return [Array]
#
# @api private
def call_safe(input)
if primitive?(input)
failed = false
result = input.each_with_object([]) do |el, output|
coerced = member.call_safe(el) { |out = el|
failed = true
out
}
output << coerced unless Undefined.equal?(coerced)
end
failed ? yield(result) : result
else
yield
end
end
# @param [Array, Object] input
# @param [#call,nil] block
#
# @yieldparam [Failure] failure
# @yieldreturn [Result]
#
# @return [Result,Logic::Result]
#
# @api public
def try(input, &block)
if primitive?(input)
output = []
result = input.map { |el| member.try(el) }
result.each do |r|
output << r.input unless Undefined.equal?(r.input)
end
if result.all?(&:success?)
success(output)
else
error = result.find(&:failure?).error
failure = failure(output, error)
block ? yield(failure) : failure
end
else
failure = failure(input, CoercionError.new("#{input} is not an array"))
block ? yield(failure) : failure
end
end
# Build a lax type
#
# @return [Lax]
#
# @api public
def lax
Lax.new(Member.new(primitive, { **options, member: member.lax, meta: meta }))
end
# @see Nominal#to_ast
#
# @api public
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
# @api private
def constructor_type
::Dry::Types::Array::Constructor
end
end
end
end
end