Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I abusing "rescue" for nil checks?

I use rescue for everything, not just for "rescuing" exceptions. I mean, I just love the way it spares me verification and double checking data.

By example, lets say I have a model Item what may or may not have a User. Then, when I want to get the owner's name of the item I write:

item.user.name rescue ""

instead of something like

item.user.nil? ? "" : item.user.name

It makes the same think, since nil.name trigger an exception that I rescue with "", but I'm not pretty sure this is good practice. It makes what I want to, and it makes it with less code, but... I don't know, all that rescue words here and there makes me feel insecure.

Is it a bad practice or is it valid abusing of the rescue keyword?

like image 506
Erik Escobedo Avatar asked Feb 04 '23 02:02

Erik Escobedo


2 Answers

I think you are abusing rescue a bit, though in Rails, there is a specific method for these issues: try. Documentation

In your case, item.user.try(:name) might be a nicer approach.

like image 180
theIV Avatar answered Feb 05 '23 15:02

theIV


I would say this is not really a good habit to get into. I've never really used this feature in Ruby since it feels like I'm just hiding error cases. It's also worth noting that you're rescuing any and all exceptions without specifying any type of expected error. It's just always looked like something which is going to make debugging down the road harder than it needs to be, although, like I've said, I've never bothered to use it myself.

like image 29
Pete Avatar answered Feb 05 '23 16:02

Pete