Issue #12515 has been updated by Matthew Kerwin.


Rodrigo Rosenfeld Rosas wrote:
> I'd just like to add a real situation where I missed a Boolean class recently.
> 
> A web request takes an array of values in a JSON encoded string and before processing the data the server-side handler will try to validate the input by comparing the elements type. If Boolean existed, the validation rule would be something like:
> 
> ~~~
> input = JSON.parse(params['value'])
> raise InvalidInput, 'size must be 6' unless input.size == 6
> raise InvalidInput, "types don't match" unless input.map(&:class) ==
>   [String, String, String, Boolean, String, Boolean]
> ~~~
> 
> As you can imagine, the validation took more effort without the existence of Boolean. Something like:
> 
> ~~~
> input.map{|x| x == false || x == true ? :boolean : x.class } ==
>   [String, String, String, :boolean, String, :boolean]
> ~~~

There's a potential religious argument here about validating against the schema before/after deserialising. Pragmatically I understand that we have a JSON parser and we don't have a JSON validator, so it's much easier to validate-later. To that end, it's also really easy to monkey-patch your way to happiness:

~~~ruby
module Boolean; end
class TrueClass; include Boolean; end
class FalseClass; include Boolean; end
[true, false, 1, nil].select {|x| Boolean === x } #=> [true, false]
~~~

There's also the fact that just because JSON has a boolean type doesn't mean Ruby has to. Ruby has procs, but you can't serialise them into JSON.

----------------------------------------
Feature #12515: Create "Boolean" superclass of TrueClass / FalseClass
https://bugs.ruby-lang.org/issues/12515#change-61157

* Author: Loren Segal
* Status: Rejected
* Priority: Normal
* Assignee: 
----------------------------------------
Since Ruby 2.4 is unifying Bignum/Fixnum into Integer (https://bugs.ruby-lang.org/issues/12005), it seems reasonable to do something similar for TrueClass / FalseClass, and create a proper Boolean hierarchy. The implementation would be fairly straightforward and should be back compat unless someone already has a "Boolean" class at toplevel out there.

Given the compatibility implications of Integer, this Boolean proposal is even less intrusive.

Sample implementation:

~~~
class Boolean < BasicObject; end
class TrueClass < Boolean; end
class FalseClass < Boolean; end
~~~




-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>