views:

61

answers:

1
def role?(role)
    return !!self.roles.find_by_name(role.to_s.camelize)
end

Can you help me understand what's happening in the code above? I'm new to Rails/Ruby.

Thanks

+3  A: 

It's negation (!) operator repeated twice.

Note that only ruby objects evaluating to false (in boolean expression) are nil and false itself.

Therefore,

  1. some_role will be true, !some_role is false and !!some_role is true again.
  2. nil is false, !nil is true and !!nil is false.

So, this is a "clever" way to check whether role returned from find_by_name is nil or not. (And therefore whether role with such name exists or not)

I guess, I don't have to tell you that doing this is bad for readability. You can always check if result is nil by normal means, like result.nil? or result == nil.

Nikita Rybak
Thanks, not sure I get it yet though. How could you rewrite this for readability, for a rails newbie?
AnApprentice
@nobosh I refactored it a bit.
Nikita Rybak
I was curious how you could rewrite it to be clearer if that makes sense? thxs
AnApprentice
@nobosh Yes, I also added to 'standard' ways to check if object is _nil_ in the end.
Nikita Rybak
Thanks - I think I get it!
AnApprentice