Class: Datacaster::HashSchema

Inherits:
Base
  • Object
show all
Defined in:
lib/datacaster/hash_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, #then, #with_context, #with_object_context, #with_runtime, #|

Constructor Details

#initialize(fields, error_key = nil) ⇒ HashSchema

Returns a new instance of HashSchema.



3
4
5
6
7
8
# File 'lib/datacaster/hash_schema.rb', line 3

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

Instance Method Details

#cast(object, runtime:) ⇒ Object



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
# File 'lib/datacaster/hash_schema.rb', line 10

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

#inspectObject



45
46
47
48
49
50
51
52
# File 'lib/datacaster/hash_schema.rb', line 45

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

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