1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-06 16:48:01 +00:00

Add Cast Common Boolean-Like Values To Booleans as a Rails til

This commit is contained in:
jbranchaud
2019-05-09 16:48:20 -05:00
parent 4e8b1d41a9
commit 7082eb4903
2 changed files with 30 additions and 1 deletions

View File

@@ -0,0 +1,28 @@
# Cast Common Boolean-Like Values To Booleans
Sometimes you have to deal with values that are supposed to represent booleans,
but they aren't actually boolean values (i.e. `"t"` instead of `true`). Rail's
`ActiveModel` has a helper for casting these common boolean-like values to
actual booleans.
```ruby
> ActiveModel::Type::Boolean.new.cast('f')
=> false
> ActiveModel::Type::Boolean.new.cast('t')
=> true
> ActiveModel::Type::Boolean.new.cast('true')
=> true
> ActiveModel::Type::Boolean.new.cast('FALSE')
=> false
> ActiveModel::Type::Boolean.new.cast(0)
=> false
> ActiveModel::Type::Boolean.new.cast(1)
=> true
> ActiveModel::Type::Boolean.new.cast(true)
=> true
> ActiveModel::Type::Boolean.new.cast(false)
=> false
```
This cast method gives you a handy way to handle all thsoe different cases.
This is available as of Rails 5+.