Sha256: 6f73014c69022aba054e2473dc27b5e176fa82dc302f8f79054f3b88033c8150

Contents?: true

Size: 1.44 KB

Versions: 18

Compression:

Stored size: 1.44 KB

Contents

module Datacaster
  class HashSchema < Base
    def initialize(fields, error_key = nil)
      @fields = fields

      @error_keys = ['.hash_value', 'datacaster.errors.hash_value']
      @error_keys.unshift(error_key) if error_key
    end

    def cast(object, runtime:)
      return Datacaster.ErrorResult(I18nValues::Key.new(@error_keys, value: object)) unless object.is_a?(Hash)

      runtime.will_check!

      errors = {}
      result = {}

      @fields.each do |key, validator|
        value =
          if object.key?(key)
            object[key]
          else
            Datacaster.absent
          end

        new_value = runtime.checked_key!(key) { validator.with_runtime(runtime).(value) }
        if new_value.valid?
          result[key] = new_value.value
        else
          errors[key] = new_value.raw_errors
        end
      end

      if errors.empty?
        # All unchecked key-value pairs are passed through, and eliminated by ContextNode
        # at the end of the chain
        result_hash = object.merge(result)
        result_hash.keys.each { |k| result_hash.delete(k) if result_hash[k] == Datacaster.absent }
        Datacaster.ValidResult(result_hash)
      else
        Datacaster.ErrorResult(errors)
      end
    end

    def inspect
      field_descriptions =
        @fields.map do |k, v|
          "#{k.inspect} => #{v.inspect}"
        end

      "#<Datacaster::HashSchema {#{field_descriptions.join(', ')}}>"
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

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