Is there a safe way to test if a value is included in an enum, i.e., without raising an exception if it does not meet constraints? And more generally, when can you not safe try? I was surprised to find that this raises a Dry::Types::ConstraintError
since I would have expected a Dry::Types::Result::Failure
. Thanks in advance for your help.
Yes, every Dry::Type
object responds to #valid?
which is a predicate that only returns booleans.
ImageContentType.valid?('image/gif') # => true
ImageContentType.valid?('text/plain') # => false
They also respond to #===
so you can use it with case
case 'application/pdf'
when Types::ImageContentType
# do something
else
# do something else
end
I don’t observe it raising on #try
, I am getting a Result object:
pry(main)> Types::ImageContentType.try('text/plain')
=> #<Dry::Types::Result::Failure input="text/plain" error=#<Dry::Types::ConstraintError: "text/plain" violates constraints (included_in?(["image/png", "image/jpeg", "image/gif", "image/webp"], "text/plain") failed)>>
If you could give me more information about how you are getting that exception from #try
, I can look into it more closely.
1 Like
Thank you for the reply @alassek! The most important thing for now is that #valid?
/#===
is exactly what I was after.