Using Nil Guards for Callbacks
Learn how to build out a nil guard inside of the update callback to fix potential program errors.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

While the last video was running, I realized I made a nasty mistake. It's good to know this mistake, so you won't make it in the future.

We can't get to the SMS task yet because if you come to the terminal and run rspec, we have a bunch of failures. There are 13 failures, and all of them point to the same line - audit_log.confirmed!. Remember we moved the audit log creation code before posts in our seeds file? That is actually a bigger bug than I thought.

To fix this, open post.rb. In the update_audit_log method, we are looking for an audit log and then changing its status to confirmed. But, what happens when there is no audit log? And if we try to call the confirmed method on something that doesn't have any value, it's throwing an error.

The good part is it's easy to fix. We are simply going to ask the application to change the status only if an audit log is returned. In other words, we are asking it to skip the confirmed method if the value of audit_log is nil. So, the updated code is:

# app/models/post.rb

def update_audit_log
  audit_log = AuditLog.where(user_id: self.user_id, start_date: (self.date - 7.days..self.date)).last
  audit_log.confirmed! if audit_log
end

This type of checking is called "Nil Guard." Though it is considered bad practice to use a ton of these throughout the application, I think it's relevant here.

Now if you run rspec, everything should pass.