Class: DataModel::Builtin::Or

Inherits:
Type
  • Object
show all
Includes:
Errors, Logging
Defined in:
lib/data_model/builtin/or.rb

Overview

Or type, allows for value to be one of several types Types will be tried in order. The first type to succeed will be used. If all types fail, the or type fails

Examples:

[:or, :string, [:array, :string]]

Defined Under Namespace

Classes: Arguments

Instance Attribute Summary

Attributes inherited from Type

#type_args, #type_registry

Instance Method Summary collapse

Methods included from Logging

#log

Methods included from Errors

#blank_error, #blank_error_message, #coerce_error, #coerce_error_message, #earliest_error, #early_error_message, #error_messages, #exclusion_error, #exclusion_error_message, #extra_keys_error, #extra_keys_error_message, #format_error, #format_error_message, #inclusion_error, #inclusion_error_message, #late_error_message, #latest_error, #max_error, #max_error_message, #min_error, #min_error_message, #missing_error, #missing_error_message, #type_error, #type_error_message

Methods inherited from Type

#initialize, #instantiate, #invoke, #type_name

Constructor Details

This class inherits a constructor from DataModel::Type

Instance Method Details

#configure(params) ⇒ void

This method returns an undefined value.

support either :string shorthand or [:string, true]

Parameters:

  • params (Array<untyped>)

    the params to configure this type



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/data_model/builtin/or.rb', line 20

def configure(params)
	if params.first.is_a?(Array)
		params = params.first
	end

	@child_types = []

	nodes = params.map { |p| Scanner.scan(Array(p)) }
	for node in nodes
		type = instantiate(node.type, args: node.args, params: node.params)
		@child_types << type
	end
end

#read(val, coerce: false) ⇒ Array(Object, Error)

read a value, and validate it

Parameters:

  • val (Object)

    the value to read

  • coerce (Boolean) (defaults to: false)

    whether to coerce the value

Returns:



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/data_model/builtin/or.rb', line 38

def read(val, coerce: false)
	args = Arguments.new(type_args)
	err = Error.new
	child_names = @child_types.map(&:type_name)

	log.debug("coerce: #{coerce} or type #{child_names} with value #{val}")

	# optional and missing
	if !args.optional && val.nil?
		err.add(missing_error(child_names))
	end

	# when missing, return early
	if val.nil?
		return [val, err]
	end

	valid = false

	for type in @child_types
		val, err = type.read(val, coerce: coerce)
		if err.empty?
			valid = true
			break
		end
	end

	if !valid
		err.add(type_error(child_names, val))
	end

	# done
	return [val, err]
end