Next-gen ruby libs! » github.com/dry-rb » website: https://dry-rb.org » forum: https://discourse.dry-rb.org
type = Dry::Types['params.time'].constrained({}).optional
type[Dry::Types::Undefined]
# => Undefined violates constraints (Undefined must be an instance of Time failed) (Dry::Types::ConstraintError)
unconstrained type works fine, is it expected behaviour?
type[nil]
doesn't raise, btw
optional
has no default value, it's just strict.nil | whatever
.optional
and set default value, if exist. So AFAIU if I'll pass nil
there will not be default value.
type = Dry::Types['params.time'].constrained(
gteq: ::Time.parse('1753-01-01 12:00:00')
)
type = type.constructor do |input|
input.respond_to?(:to_time) ? input.to_time : input
end
TYPE = type.optional.meta(omittable: true)
User = Dry.Struct do
attribute :time, type
end
p User.new(time: nil)
# => [User.new] nil (NilClass) has invalid type for :time violates constraints (nil must be an instance of Time failed) (Dry::Struct::Error)
struct = Dry.Struct do
attribute :time, Dry::Types['string']
end
struct = struct.constructor { |input| input }
struct.optional
# => undefined method `optional' for #<Dry::Struct::Constructor type=#<Class:0x000000000175bf10>> (NoMethodError)
hash = Dry::Types['hash'].constructor { |input| { x: 1 } }
coercible = Dry::Types['coercible.hash'].constructor { |input| { x: 1 } }
p hash['foo'] # => { x: 1 }
p coercible['foo'] # => can't convert String into Hash (TypeError)
hash = Dry::Types['hash'].constructor { |input| { x: 1 } }
.constructor { |input| { y: 2 } }
p hash['foo'] # => { y: 2 }
f . g = \x -> f(g(x))
(read "f after g")