I’m looking for a good shortcut for Nil checking in my Rails views. I’ve seen other questions on SO about this, but none seem to simplify this as much as I’d like. What I’d like is a short syntax to return an empty string "" if a particular value is nil, otherwise return the value.
There is a suggestion here which I am inclined to try out. It basically allows a statement like this:
user.photo._?.url
— or —
user.photo.url._?
Is this a good idea or is it fraught with peril?
My other option would be to handle nils on my models, but that seems too global.
The idiomatic Ruby way to accomplish this is the
||operator, which will return the value of the right-hand expression if the left-hand expression isnil(orfalse):Any moderately experienced Ruby programmer will understand exactly what that does. If you write a custom
_?method, I now have to go look up the purpose of that method and remember what it does and hope that it always does the right thing. I generally find that sticking to idiomatic code is far more beneficial than saving a few keystrokes here and there.