Class: DataModel::Builtin::Time

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

Overview

A time type

Defined Under Namespace

Classes: Arguments

Instance Attribute Summary

Attributes inherited from Type

#type_args, #type_registry

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, #type_name

Constructor Details

This class inherits a constructor from DataModel::Type

Instance Method Details

#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:



17
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
# File 'lib/data_model/builtin/time.rb', line 17

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

	# missing, but allowed, don't do any more checks
	if val.nil? && args.optional
		return [val, err]
	end

	# missing, but not allowed, don't do any more checks
	if val.nil?
		err.add(missing_error(type_name))
		return [val, err]
	end

	# coercion is enabled, and the value is a string, try to parse it
	if val.is_a?(String) && coerce
		begin
			val = Time.parse(val)
		rescue ArgumentError
			err.add(type_error(type_name, val))
			return [val, err]
		end
	end

	# not a date, don't do any more checks
	if !val.is_a?(Time)
		err.add(type_error(type_name, val))
		return [val, err]
	end

	# date is before the earliest point allowed
	if args.earliest && (val < args.earliest)
		error = earliest_error(args.earliest, val)
		err.add(error)
	end

	# date is after the latest point allowed
	if args.latest && (val > args.latest)
		error = latest_error(args.latest, val)
		err.add(error)
	end

	return [val, err]
end