CoerceBoolean
Coerce boolean-like values into their correct values. Values to use are inspired by ActiveModel::Type::Boolean
Coercion
Coercion behavior is uses Ruby's boolean semantics with additional parsing.
-
niland empty strings are coerced tonil - Any value in
CoerceBoolean::FALSE_VALUESwill be coerced to false - All other values will be coerced to
true- This includes
0as aFloatorBigDecimal; onlyInteger0is false
- This includes
If the object passed to .from responds to to_boolean, coercion will be run
against the result of to_boolean
Strict Mode
Strict Mode always returns a boolean
-
niland empty strings are coerced tofalse - All other values follow the coercion rules above
to_bool
This library adds to_bool to the Object class to allow users to create
explicit and implicit conversions in the same manner as to_s and to_str
- There is both a class method (
.to_bool(...)) and an instance method (#to_bool(strict: false)) -
.to_boolwill always directly return true unless overridden -
#to_boolwill callCoerceBoolean.fromwithselfandstrictas args
Examples
CoerceBoolean.from("false") # falseCoerceBoolean.from("true") # trueCoerceBoolean.from(1) # trueCoerceBoolean.from(0) # falseCoerceBoolean.from("") # nilCoerceBoolean.from(nil) # nilCoerceBoolean.from(nil, strict: true) # falseSomeClass.to_bool # true"".to_bool # nil"".to_bool(strict: true) # false0.to_bool # false0.0.to_bool # true0.1.to_bool # true
Installation
Add this line to your application's Gemfile:
gem 'coerce_boolean'And then execute:
$ bundleOr add and install directly with bundler:
bundle add 'coerce_boolean'Or install it directly with:
$ gem install coerce_booleanLicense
The gem is available as open source under the terms of the MIT License.