The Spaghetti Refactory Established 2015

Handling nil values with #to_s

Occasionally, I have run into 500 server errors because there is an object attribute that is nil and I try to run a method on it. This tended to happen in my jbuilder files for returning API responses where the mobile app needed data in a certain format. Here's the simplest way to fix this:

nil.to_s 
#=> Outputs “”

Even if I wasn't getting server errors, in jbuilder files, often returning a null value in the response can be problematic for whatever app is using that response, so if there’s a chance an object attribute is nil, instead of doing an if/else, simple run #to_s on the attribute. I’m guessing this might be a slight performance hit, but probably not much more than an if/else statement would be.

Tags