I've frequently used this pattern to extend the core behavior of Ruby to make it easier to deal with converting arbitrary data types to boolean values, which makes it really easy to deal with varying URL parameters, etc.
class String
def to_boolean
ActiveRecord::Type::Boolean.new.cast(self)
end
end
class NilClass
def to_boolean
false
end
end
class TrueClass
def to_boolean
true
end
def to_i
1
end
end
class FalseClass
def to_boolean
false
end
def to_i
0
end
end
class Integer
def to_boolean
to_s.to_boolean
end
end
So let's say you have a parameter foo
which can be:
- an integer (0 is false, all others are true)
- a true boolean (true/false)
- a string ("true", "false", "0", "1", "TRUE", "FALSE")
- nil
Instead of using a bunch of conditionals, you can just call foo.to_boolean
and it will do the rest of the magic for you.
In Rails, I add this to an initializer named core_ext.rb
in nearly all of my projects since this pattern is so common.
## EXAMPLES
nil.to_boolean == false
true.to_boolean == true
false.to_boolean == false
0.to_boolean == false
1.to_boolean == true
99.to_boolean == true
"true".to_boolean == true
"foo".to_boolean == true
"false".to_boolean == false
"TRUE".to_boolean == true
"FALSE".to_boolean == false
"0".to_boolean == false
"1".to_boolean == true
true.to_i == 1
false.to_i == 0
true
orfalse
or is it enough if the result is truthy or falsey? If the latter, thenfalse
is already falsey, and bothtrue
and'true'
are truthy, so the only value for which the result is not already correct, is'false'
:if input == 'false' then true else input end
should do it.!!(if input == 'false' then true else input end)
. The second!
converts the return value to a boolean that is the opposite of what you want; the first!
then makes the correction. This " trick" has been around a long time. Not everyone is fond of it.