Class: Datacaster::ArraySchema
- Defined in:
- lib/datacaster/array_schema.rb
Instance Method Summary collapse
- #cast(array, runtime:) ⇒ Object
-
#initialize(element_caster, error_keys = {}) ⇒ ArraySchema
constructor
A new instance of ArraySchema.
- #inspect ⇒ Object
Methods included from Mixin
#&, #*, #call, #call_with_runtime, #cast_errors, #i18n_key, #i18n_map_keys, #i18n_scope, #i18n_vars, #then, #with_context, #with_object_context, #with_runtime, #|
Constructor Details
#initialize(element_caster, error_keys = {}) ⇒ ArraySchema
Returns a new instance of ArraySchema.
3 4 5 6 7 8 9 10 11 |
# File 'lib/datacaster/array_schema.rb', line 3 def initialize(element_caster, error_keys = {}) @element_caster = element_caster @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
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/datacaster/array_schema.rb', line 13 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? 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
33 34 35 |
# File 'lib/datacaster/array_schema.rb', line 33 def inspect "#<Datacaster::ArraySchema [#{@element_caster.inspect}]>" end |