to_bool rails plugin

In our rail application we do a lot of string conversions to other data types, including Boolean. Unfortunately, ruby does not provide a conversion method to_bool (which I find rather strange, to be honest).

Based a blog post by Chris Roos in October 2006, we developed a rails plugin that enables the “to_bool” conversion.

“to_bool” works on the strings “true” and “false” and any capitalisation of these, and on numbers, as well as on nil. Other strings raise an ArgumentError.

Examples are as follows:

'true'.to_bool #-> true
'TrUe'.to_bool #-> true
true.to_bool #-> true
1.to_bool #-> true
5.to_bool #-> true
-9.to_bool #-> true
nil.to_bool #-> false
'false'.to_bool #-> false
'FaLsE'.to_bool #-> false
false.to_bool #-> false
0.to_bool #-> false

You can find the plugin here as a tarball. To install it, simply decompress the to_bool directory into your vendor/plugins directory.

Leave a Reply

Your email address will not be published. Required fields are marked *