Module: Qwack::BaseHash

Includes:
Base
Defined in:
lib/qwack/base_hash.rb

Overview

Base module for user defined hashes

Instance Method Summary collapse

Methods included from Base

#mock!, #validate!

Instance Method Details

#attribute_validation_errors(input, path, key, errors) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/qwack/base_hash.rb', line 21

def attribute_validation_errors(input, path, key, errors)
  if !attributes.key?(key)
    errors << { path: path, name: name, desc: 'Extraneous keys', item: key }
  elsif !input.key?(key)
    errors << { path: path, name: name, desc: 'Missing non-optional key', item: key } \
      unless attributes[key][:optional] == true
  elsif input[key].nil?
    errors << { path: path, name: name, desc: 'Key cannot be null', item: key } \
      unless attributes[key][:null] == true
  else
    errors.append(*attributes[key][:type].validation_errors(input[key], "#{path}.#{key}"))
  end
end

#attributesObject



10
11
12
13
14
# File 'lib/qwack/base_hash.rb', line 10

def attributes
  ancestors.reverse.each_with_object({}) do |ancestor, obj|
    obj.merge!(ancestor.own_attributes) if ancestor.respond_to?(:own_attributes)
  end
end

#mock(input = nil) ⇒ Object



45
46
47
48
49
# File 'lib/qwack/base_hash.rb', line 45

def mock(input = nil)
  attributes.each_with_object({}) do |(key, conf), obj|
    obj[key] = conf[:type].mock(input&.fetch(key, nil) || conf[:mock])
  end
end

#own_attributesObject



16
17
18
# File 'lib/qwack/base_hash.rb', line 16

def own_attributes
  @own_attributes ||= {}
end

#validation_errors(input, path = 'root') ⇒ Object

rubocop:enable Metrics/AbcSize, Metrics/MethodLength



36
37
38
39
40
41
42
43
# File 'lib/qwack/base_hash.rb', line 36

def validation_errors(input, path = 'root')
  return [{ path: path, name: name, desc: 'Is not a Hash', item: input }] \
    unless input.is_a?(::Hash)

  (attributes.keys + input.keys).uniq.each_with_object([]) do |key, errors|
    attribute_validation_errors(input, path, key, errors)
  end
end