All your problems are nil

Your logs are littered with them. Like an apparition, the Rails screen of death appears to haunt your sleep. /execute/this/action/ works sometimes, but not all the time. My friends, your problems are nil.

In my growing time with Ruby and Rails I’ve noticed a good deal of reoccurring themes. Themes may be to grand . . . mistakes are more accurate. In working with my own and other people’s code, an error that keeps coming up, and is often responsible for the majority of errors on a site looks something like this:


  undefined method `amplify' for nil:NilClass

  [RAILS_ROOT]/app/controllers/belch_controller.rb:102:in `make_that_belch_loud'

The undefined method error is everywhere. And it can cause an endless amount of frustration as a bourgeoning Ruby developer. This foul thing arrives out of Ruby’s beauty. Ruby is very loosely typed, meaning the variable called ‘integer’ could very well be a string, or even an ActiveRecord model. There are various ways to test this:

integer = 'Not so much'
integer.is_a?(Fixnum) #=> false
integer.class == String #=> true

So in an application where not everyone is as knowledgeable is you, and users are constantly throwing junk in your code’s face, you’ll get a lot of variables that aren’t what they claim to be.

Above, the method make_that_belch_loud takes a single argument which we assume to be of the class Belch. Taking this for granted, we’re trying to call the amplify method of the Belch object. However, this assumption cause the application fart above – not what we expected. This could have happened for many reasons. Someone didnt fill out a form field; a bot is trying to access the site without sending the right vars. Of course its always a good idea to look up the execution tree and see where things went wrong. If for some reason you can’t validate before the method, or that just isnt enough, there is always the most basic and root solution.

def make_that_belch_loud(belch)
  return unless belch
  # or even more specific
  return unless belch and belch.is_a?(Belch)

Of course checking error logs in production is no substitution for preemptive testing, but there are often errors like this you just don’t expect.

Comments are closed.

About

QuirkeyBlog is Aaron Quint's perspective on the ongoing adventure of Code, Life, Work and the Web.

twitter/@aq.

instagram/@quirkey.

github/quirkey.

QuirkeyBlog is proudly powered by WordPress

Categories