Sha256: 0d72b224cee4b84cfe8fab1cc7cdc787ddc23e9a9dbacd2e07defca0a4eaaa28

Contents?: true

Size: 1.84 KB

Versions: 3

Compression:

Stored size: 1.84 KB

Contents

# typed: strict

module DataModel
	class Builtin::String < Type
		include Errors

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

		class Arguments < T::Struct
			prop :optional, T::Boolean, default: false
			prop :allow_blank, T::Boolean, default: true
			prop :format, T.nilable(T.any(String, Regexp, TFormatter)), default: nil
			prop :included, T::Array[String], default: []
			prop :excluded, T::Array[String], 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(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
	end
end

Version data entries

3 entries across 3 versions & 1 rubygems

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