dry-rb / dry-logic

Predicate logic with rule composition
https://dry-rb.org/gems/dry-logic/
MIT License
179 stars 66 forks source link

Check something is a string before checking its format #102

Closed matthewdavidlloyd closed 2 years ago

matthewdavidlloyd commented 2 years ago

Currently, checking if a non-string is a UUID or a URI causes the following error to be thrown:

TypeError: no implicit conversion of Hash into String

This corrects that and means it instead behaves like a failed predicate.

flash-gordon commented 2 years ago

I don't think such checks give much, there are plenty of ways to ruin a program by providing incorrect values. Guarding against them 1) makes code more complex 2) slows down the program 3) reduces the visibility of type errors. If you really want to check if something's a string then you should use composition instead

extend Dry::Logic::Builder

check = build do
  nil? | str? & format?(/foo/)
end
 :001 > check.(Object.new).success?
 => false 
 :002 > check.(nil).success?
 => true 
 :003 > check.('bar').success?
 => false 
 :004 > check.('foo1').success?
 => true