Checking for null strings in Rails mode

I am looking for a good shortcut for checking Nil in my Rails submissions. I saw other questions about this, but no one seems to simplify this as I would like. I would like the short syntax to return an empty string "" if the specific value is nil, otherwise return the value.

There is a suggestion here that I tend to try. This basically allows you to do the following:

 user.photo._?.url 

- or -

 user.photo.url._? 

Is this a good idea or is it fraught with danger?

My other option would be to handle nils on my models, but that seems too global.

+4
source share
5 answers

The Ruby idiomatic way to do this is with the || which will return the value of the right expression if the left expression is nil (or false ):

 puts(user.photo.url || '') 

Any moderately experienced Ruby programmer will understand exactly what this does. If you write your own method _? , now I have to look for this method and remember what it does, and hope that it always does the right thing. I usually find that sticking with idiomatic code is much more profitable than saving a few keystrokes here and there.

+3
source

You should check the try method, which runs the provided method for the object and returns a value if the object in question is non-zero. Otherwise, it will just return zero.

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) 

See this blog post for more details.

+5
source

try the following:

 user && user.photo && user.photo.url.present? 

This will not explode if the user is zero or user.photo is zero

+1
source

How about using nil?

 someObject.nil? # true if someOBj is nil 

Or I do not understand what you want?

0
source

I suspect your options are problematic, because if the photo is zero, both of your operators should return an Undefined method.

You do not even need to check ".nil?". Since you assumed that your check is in the view, and not in the controller, I suppose you check the @instance variable, which will always be zero if undefined. So simple:

 if @someObject ... else ... 

If you put the condition in your controller, then use the @instance variable again, and you will always have at least zero if undefined.

0
source

All Articles