Class: Datacaster::ArraySchema
- Inherits:
-
Base
- Object
- Base
- Datacaster::ArraySchema
show all
- Defined in:
- lib/datacaster/array_schema.rb
Instance Method Summary
collapse
Methods included from Mixin
#&, #*, #call, #call_with_runtime, #cast_errors, #i18n_key, #i18n_map_keys, #i18n_scope, #i18n_vars, #json_schema, #json_schema_attributes, #then, #to_json_schema_attributes, #with_context, #with_object_context, #with_runtime, #|
Constructor Details
#initialize(element_caster, error_keys = {}, allow_empty: false) ⇒ ArraySchema
Returns a new instance of ArraySchema.
3
4
5
6
7
8
9
10
11
12
|
# File 'lib/datacaster/array_schema.rb', line 3
def initialize(element_caster, error_keys = {}, allow_empty: false)
@element_caster = element_caster
@allow_empty = allow_empty
@not_array_error_keys = ['.array', 'datacaster.errors.array']
@not_array_error_keys.unshift(error_keys[:array]) if error_keys[:array]
@empty_error_keys = ['.empty', 'datacaster.errors.empty']
@error_keys.unshift(error_keys[:empty]) if error_keys[:empty]
end
|
Instance Method Details
#cast(array, runtime:) ⇒ Object
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
# File 'lib/datacaster/array_schema.rb', line 14
def cast(array, runtime:)
return Datacaster.ErrorResult(I18nValues::Key.new(@not_array_error_keys, value: array)) if !array.respond_to?(:map) || !array.respond_to?(:zip)
return Datacaster.ErrorResult(I18nValues::Key.new(@empty_error_keys, value: array)) if array.empty? && !@allow_empty
runtime.will_check!
result =
array.map.with_index do |x, i|
runtime.checked_key!(i) do
@element_caster.with_runtime(runtime).(x)
end
end
if result.all?(&:valid?)
Datacaster.ValidResult(result.map!(&:value))
else
Datacaster.ErrorResult(result.each.with_index.reject { |x, _| x.valid? }.map { |x, i| [i, x.raw_errors] }.to_h)
end
end
|
#inspect ⇒ Object
41
42
43
|
# File 'lib/datacaster/array_schema.rb', line 41
def inspect
"#<Datacaster::ArraySchema [#{@element_caster.inspect}]>"
end
|
#to_json_schema ⇒ Object
34
35
36
37
38
39
|
# File 'lib/datacaster/array_schema.rb', line 34
def to_json_schema
JsonSchemaResult.new({
'type' => 'array',
'items' => @element_caster.to_json_schema
})
end
|