Search code examples
rubynullrescue

How do I rescue a method when there is nil user?


From time to time I have user.id == nil. And when this happens my lookup fails. What is the most practical way to rescue this code? and what do you typically return when this happens?

def lookup  
  @data[user.id]["email"]
end

Say a mail method is using the returned value

email(lookup).deliver

Solution

  • begin
      @data[user.id]["email"]
    rescue Exception
      nil
    end
    

    or you might be able to do

    @date[user.try(:id)]["email"]
    

    which will just return nil if user is nil and you call id on it.

    The real problem here is that you've got a code smell. Whatever class owns the lookup method knows too much about the implementation details of @data. I can't recommend a fix without more code, but I'd suggest writing a method/class that only knows how to pull the email out of data. Something like:

    @data.get_email_for_user
    

    That way this class wouldn't have to worry about whether or not user is nil. It only has to worry about returning the email.