Sha256: fb5be71aa913f6613671e8f020f8778975829016040afb499b720a6122e6fc27

Contents?: true

Size: 1.33 KB

Versions: 4

Compression:

Stored size: 1.33 KB

Contents

# typed: strict

module DataModel
	class Builtin::Symbol < Type
		include Errors

		class Arguments < T::Struct
			prop :optional, T::Boolean, default: false
			prop :included, T::Array[Symbol], default: []
			prop :excluded, T::Array[Symbol], default: []
		end

		sig { override.params(val: Object, coerce: T::Boolean).returns(TTypeResult) }
		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(Symbol))
				return [val, err]
			end

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

			# attempt coercion
			if !val.is_a?(Symbol) && coerce
				if val.is_a?(String)
					val = val.intern
				elsif val.respond_to?(:to_sym)
					val = T.unsafe(val).to_sym
				else
					err.add(coerce_error(Symbol, val))
					return [val, err]
				end
			end

			val = T.cast(val, Symbol)

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

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

			# done
			return [val, err]
		end
	end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
data_model-0.4.0 lib/data_model/builtin/symbol.rb
data_model-0.3.0 lib/data_model/builtin/symbol.rb
data_model-0.2.0 lib/data_model/builtin/symbol.rb
data_model-0.1.0 lib/data_model/builtin/symbol.rb