Class: GoldenFleece::ValidatorContext

Inherits:
Object
  • Object
show all
Includes:
Utility
Defined in:
lib/golden_fleece/validations/validator_context.rb

Constant Summary

Constants included from Utility

Utility::FALSE_VALUES

Instance Method Summary collapse

Methods included from Utility

#build_json_path, #cast_boolean, #deep_stringify_keys, #error_suffix

Constructor Details

#initialize(record, attribute, persisted_json, schemas, parent_path) ⇒ ValidatorContext

Returns a new instance of ValidatorContext.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/golden_fleece/validations/validator_context.rb', line 12

def initialize(record, attribute, persisted_json, schemas, parent_path)
  @persisted_json = persisted_json
  @schemas = schemas
  @parent_path = parent_path
  persisted_keys = if persisted_json && persisted_json.keys
    persisted_json.keys.map(&:to_sym)
  else
    []
  end
  schemas_keys = schemas ? schemas.keys : []
  @validatable_keys = (persisted_keys + schemas_keys).uniq
  @record = record
  @attribute = attribute
  @errors = []
end

Instance Method Details

#validateObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/golden_fleece/validations/validator_context.rb', line 28

def validate
  validatable_keys.each do |key|
    path = build_json_path(parent_path, key)

    if validate_key key, path
      schema = schemas[key]
      value = schema.value.compute(record)

      validate_type(value, schema.types, path)
      validate_format(value, schema.format, path)

      # If the key's value is a nested JSON object, recurse down
      errors << ValidatorContext.new(record, attribute, (persisted_json ? persisted_json[key.to_s] : nil), schemas[key], path).validate if value.is_a?(Hash)
    end
  end

  errors.flatten
end