Reputation: 1415
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.
Upvotes: 4
Views: 1776
Reputation: 14171
try this:
user && user.photo && user.photo.url.present?
This will not blow up if user is nil or user.photo is nil
Upvotes: 1
Reputation: 3915
You should check try
method which runs a provided method on the object and returns the value if the object in question is not nil. Otherwise it'll just return nil.
Example
# We have a user model with name field
u = User.first
# case 1 : u is not nil
u.try(:name)
=> Foo Bar
# case 2 : u is nil
u.try(:name)
=> nil
# in your case
user.photo.try(:url)
For details have a look at this blog post.
Upvotes: 5
Reputation: 14983
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 is nil
(or false
):
puts(user.photo.url || '')
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.
Upvotes: 3
Reputation: 4451
I suspect your options are problematic, because if photo is nil, both of your statements should return 'Undefined method'.
You shouldn't even need to check for '.nil?'. Since you implied your checking is in the view, and not in the controller, I imagine you are checking an @instance variable, which will always be nil if undefined. So just do:
if @someObject
...
else
...
If you are putting the conditional in your controller, then again, just use an @instance variable and you'll always have at least nil, if undefined.
Upvotes: 0
Reputation: 14171
What about just using nil?
someObject.nil? # true if someOBj is nil
Or am I misunderstanding what you want?
Upvotes: 0