Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for nil strings in Rails view

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.

like image 988
jn29098 Avatar asked Jan 16 '23 21:01

jn29098


1 Answers

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.

like image 58
Kulbir Saini Avatar answered Jan 27 '23 09:01

Kulbir Saini