Class: DataModel::Builtin::String

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

Defined Under Namespace

Classes: Arguments

Constant Summary collapse

TFormatter =
T.type_alias { T.proc.params(val: String).returns(T::Boolean) }

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

#configure, #initialize, #instantiate, #invoke

Constructor Details

This class inherits a constructor from DataModel::Type

Instance Method Details

#read(val, coerce: false) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/data_model/builtin/string.rb', line 18

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

	# optional & missing
	if args.optional && val.nil?
		return [val, err]
	end

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

	# type error
	if !val.is_a?(String) && !coerce
		err.add(type_error(String, val))
		return [val, err]
	end

	# attempt coercion
	if !val.is_a?(String) && coerce
		begin
			val = String(val)
		rescue TypeError
			err.add(coerce_error(String, val))
			return [val, err]
		end
	end

	val = T.cast(val, String)

	# format
	fmt = args.format
	if fmt
		case fmt
		when String
			if !val.match?(fmt)
				err.add(format_error(fmt, val))
			end
		when Regexp
			if !val.match?(fmt)
				err.add(format_error(fmt, val))
			end
		when Proc
			if !fmt.call(val)
				err.add(format_error("<Custom Proc>", val))
			end
		end
	end

	# inclusion
	if args.included.any? && !args.included.include?(val)
		err.add(inclusion_error(args.included))
	end

	# exclusion
	if args.excluded.any? && args.excluded.include?(val)
		err.add(exclusion_error(args.excluded))
	end

	# allow blank
	if !args.allow_blank && val.empty?
		err.add(blank_error)
	end

	# done
	return [val, err]
end