views:

94

answers:

1

Hello, 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?

+3  A: 

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).

Chris
Answer is ok, but `nil == false` will not return `true`!
Marcel J.
Thanks Marcel, I've updated the answer.
Chris
Very nice! is it possible to use the TRY method on something like "permissions.find_by_project_id(projectid).role.name" ?
AnApprentice
AnApprentice
`permission = permissions.find_by_project_id(projectid);` `if permission.try(:role).try(:name)`
Chris
So you set a var and then use that in the IF statement? Interesting. Thxs
AnApprentice
You don't have to use a variable, though if you'll be using the permissions object again it certainly makes sense to have it handy rather than typing out `permissions.find_by_project_id(projectid)` all the time.
Chris