Parse a String to a Boolean in Ruby on Rails

Recently, I’ve been working on a headless Rails project, that is, one without a database. All the data to and from the app goes by way of an API. That API, unfortunately, doesn’t follow REST conventions so it’s been up to me to write a lot of the methods that I need. APISmith, the gem I’ve been using to help parse the responses that come back from the API, does a great job at simplifying that process (If you’re interested, read more here). By providing you the ability to define custom transformers to automatically convert or parse the data that you receive, APISmith allows you to take a strange or bloated response and pare it down to just the data you need represented as a neat little Ruby object. Genius.

Just this morning though, I came across one of the responses from the API that seems to be a little confused. There are a few attributes that should be represented as booleans, but are being returned as 0 and 1 sometimes, as true and false other times, but not matter what the response value it’s always returned as a String. As you can imagine, this can cause a little trouble; I needed to know what the actual true or false value was, not some representation as a string. So I looked around for to_boolean method and not finding a satisfactory one I combined a few ideas I had seen in others and made a quick and dirty String extension for Rails.

It’s simple, it’s quick and it does the job. Just drop the file into the /config/initializers directory and you’re done. One note, I’ve set it up to convert blank strings into false values, if you don’t want that, just remove the middle part of the return false line.

This site was developed with HTML5 and CSS3 and utilizes the latest responsive web design principles (Go ahead, resize your browser window, I dare you.). if you’re not using one of the latest browsers (Safari, Chrome, or Firefox) this site will probably look completely battered. I have no idea since I haven’t opened it on a Windows machine or with Internet Explorer, but if this site does look busted it’s a sure sign that it’s time to upgrade your un-safe, slow, broken-ass browser.