AnApprentice
AnApprentice

Reputation: 111070

Rails 3 - IF Statement which doesn't break on NIL

I have the following if statement:

if !projectid_viewing.nil? && !user.role(projectid_viewing).nil? && user.role(projectid_viewing) == 'admin'

What I'm trying to do with the above, is not have the if break is projectid_viewing or user.role are nil. projectid_viewing seems to work great but user.role keeps breaking, giving the following error:

undefined method `role' for nil:NilClass

Can you help me with the if statement and is there a more elegant way to write the statement?

Upvotes: 2

Views: 2728

Answers (1)

Chris
Chris

Reputation: 10378

You need to make sure that user is not nil as well.

Note that in Ruby, a value of nil in a conditional statement will be interpreted as false. Thus, if you use a variable with a nil value in a conditional statement, it will also evaluate to false. Knowing this, you can simplify statements like !projectid_viewing.nil? to just the name of the variable, and it will work just the same.

if projectid_viewing && user && user.role(projectid_viewing) == 'admin'

The above is just plain Ruby, but you said you're using Rails 3. Rails has a neat little method: Object#try. It would allow you to simplify this statement further to the following:

if projectid_viewing && user.try(:role, projectid_viewing) == 'admin'

The Object#try method will protect you if the value of user is nil, and that entire second part of the expression will return nil (i.e., false).

Upvotes: 5

Related Questions