tobyink / p5-type-tiny

Perl 5 distribution Type-Tiny; see homepage for downloads and documentation.
https://typetiny.toby.ink/
54 stars 48 forks source link

BoolLike in Types::TypeTiny should check `!` overloading to support boolean.pm #144

Open bpj opened 1 year ago

bpj commented 1 year ago

BoolLike in Types::TypeTiny should check for ! overloading as well as bool and 0+ because that is what boolean.pm overloads (don't ask me why!) YAML::PP supports the use of boolean.pm for booleans and it makes sense to use that when JSON interoperability is not needed because it is a smaller dependency and has a better interface: easy conversion to/check for booleans and its functions/constants can be imported.

bpj commented 10 months ago

Anything?

bpj commented 3 months ago

I still stand by my request but meanwhile I have found that the code below DWIM in 95% of cases with a minimum of fuss, so for workaround reference:

use Types::Standard qw[Enum Object];
use boolean;
use JSON;

# Anything with a string value of 0 or 1

my $BoolishStr = Enum->of( 0, 1 );

my $BoolishObj = Object->stringifies_to($BoolishStr)->create_child_type(
  name         => 'BoolishObj',
  display_name => "Object (stringifies to $BoolishStr)",
);

my $Boolish
    = ( $BoolishStr | $BoolishObj )->create_child_type( name => 'Boolish' );

for my $val ( 1, 0, true, JSON::true, [], 'true' ) {
  say ref($val) || "'$val'";
  say for @{ $Boolish->validate_explain($val) // ['pass'] };
}

The icky case may for example be a Path::Tiny object to a directory 0. You never know what User does but lately I haven't used a union of Overload types, nor could I be arsed to write a proper OverloadAny type which would accept a value which overloads any of a number of operations, or the like.