Class: DataModel::Builtin::Array

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

Defined Under Namespace

Classes: Arguments

Constant Summary

Constants included from Errors

Errors::TClassCtx, Errors::TClassValueCtx, Errors::TErrorMessageBuilder, Errors::TErrorMessages, Errors::TFormatCtx, Errors::TSetCtx, Errors::TTemporal, Errors::TWithinCtx, Errors::TWithinTemporalCtx

Constants inherited from Type

Type::TArguments, Type::TTypeParams, Type::TTypeResult

Instance Attribute Summary

Attributes inherited from Type

#type_args

Instance Method Summary collapse

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

Constructor Details

This class inherits a constructor from DataModel::Type

Instance Method Details

#child_typeObject



30
31
32
33
34
35
36
# File 'lib/data_model/builtin/array.rb', line 30

def child_type
  if @child_type.nil?
    raise "children not configured"
  end

  return @child_type
end

#configure(params) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/data_model/builtin/array.rb', line 17

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

  params = T.cast(params, TSchema)
  node = Scanner.scan(params)
  type = instantiate(node.type, args: node.args, params: node.params)

  @child_type = T.let(type, T.nilable(Type))
end

#read(val, coerce: false) ⇒ Object



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/array.rb', line 39

def read(val, coerce: false)
  args = Arguments.new(type_args)
  err = Error.new

  if val.nil? && !args.optional
    err.add(missing_error(Array))
    return [val, err]
  end

  if coerce && args.wrap_single_value
    val = Array(val)
  end

  if !val.is_a?(Array)
    err.add(type_error(Array, val))
    return [val, err]
  end

  coerced = []

  for i in 0...val.length
    child_val = T.let(val[i], Object)
    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