Class: DataModel::Builtin::Array
- Includes:
- Errors
- Defined in:
- lib/data_model/builtin/array.rb
Overview
Array is a type that contains a list of other types.
Defined Under Namespace
Classes: Arguments
Instance Attribute Summary collapse
-
#child_type ⇒ Type
readonly
get the child Type.
Attributes inherited from Type
Instance Method Summary collapse
-
#configure(params) ⇒ void
configure how children will be read.
-
#read(val, coerce: false) ⇒ Array(Object, Error)
read a value, and validate it.
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 Attribute Details
#child_type ⇒ Type (readonly)
get the child Type
21 22 23 |
# File 'lib/data_model/builtin/array.rb', line 21 def child_type @child_type end |
Instance Method Details
#configure(params) ⇒ void
This method returns an undefined value.
configure how children will be read
26 27 28 29 30 31 32 33 34 35 |
# File 'lib/data_model/builtin/array.rb', line 26 def configure(params) if params.first.is_a?(Array) params = params.first end node = Scanner.scan(params) type = instantiate(node.type, args: node.args, params: node.params) @child_type = type end |
#read(val, coerce: false) ⇒ Array(Object, Error)
read a value, and validate it
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 72 73 74 75 76 77 78 |
# File 'lib/data_model/builtin/array.rb', line 41 def read(val, coerce: false) args = Arguments.new(type_args) err = Error.new if val.nil? && !args.optional err.add(missing_error(type_name)) return [val, err] end if coerce && args.wrap_single_value val = Array(val) end if !val.is_a?(Array) err.add(type_error(type_name, val)) return [val, err] end # no child type configured, allow any array if child_type.nil? return [val, err] end coerced = [] for i in 0...val.length child_val = val[i] child, child_err = child_type.read(child_val, coerce:) if child_err err.merge_child(i.to_s.to_sym, child_err) end coerced << child end result = coerce ? coerced : val return [result, err] end |