Sha256: f01ff1bcd80cfda2ac8eadef5b957166305a69ae957230e4f7d511e5dec8933e

Contents?: true

Size: 1.21 KB

Versions: 18

Compression:

Stored size: 1.21 KB

Contents

module Datacaster
  class ArraySchema < Base
    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

    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

    def inspect
      "#<Datacaster::ArraySchema [#{@element_caster.inspect}]>"
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
datacaster-4.1.0 lib/datacaster/array_schema.rb
datacaster-4.0.1 lib/datacaster/array_schema.rb
datacaster-3.3.1 lib/datacaster/array_schema.rb
datacaster-3.3.0 lib/datacaster/array_schema.rb
datacaster-3.2.7 lib/datacaster/array_schema.rb
datacaster-3.2.6 lib/datacaster/array_schema.rb
datacaster-3.2.5 lib/datacaster/array_schema.rb
datacaster-3.2.4 lib/datacaster/array_schema.rb
datacaster-3.2.3 lib/datacaster/array_schema.rb
datacaster-3.2.2 lib/datacaster/array_schema.rb
datacaster-3.2.1 lib/datacaster/array_schema.rb
datacaster-3.2.0 lib/datacaster/array_schema.rb
datacaster-3.1.5 lib/datacaster/array_schema.rb
datacaster-3.1.3 lib/datacaster/array_schema.rb
datacaster-3.1.2 lib/datacaster/array_schema.rb
datacaster-3.1.1 lib/datacaster/array_schema.rb
datacaster-3.1.0 lib/datacaster/array_schema.rb
datacaster-3.0.0 lib/datacaster/array_schema.rb