AnApprentice
AnApprentice

Reputation: 111070

What is this line of Rails code doing?

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

Upvotes: 1

Views: 176

Answers (2)

DavidNorth
DavidNorth

Reputation: 450

This is more readable. No need for the 'self' or 'return'. 'present?' is the opposite of 'nil?' so no negation is required.

def role?(role)
  roles.find_by_name(role.to_s.camelize).present?
end

Upvotes: 1

Nikita Rybak
Nikita Rybak

Reputation: 68036

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.

Upvotes: 4

Related Questions