Short Circuit Evaluation is your friend here. It means a false before an &&
will drop you to the else
much like an if
would have. It just leaves you with only one else
instead of many. As an example here's a cleaner way to layout the code:
def set_tenant
if current_user
&& current_user.tenant_id.present?
&& current_user.tenants.include?(current_user.tenant)
current_account = current_user.tenant
set_current_tenant(current_account)
else
set_current_tenant(nil)
end
end
If prefer &&
over if
chains in cases like this. It makes the code look simpler.
This layout shows the structure of the logic and I find it more readable than the stream of word wrapped noise you get if you jam all the &&
s on the same line. Ruby doesn't care about whitespace so it works but your style guide might have something to say about it.
If it doesn't then look for examples in the existing code base and conform to that. Here are some examples of multi-line ruby if's from stack overflow.
And, as Thomas Owens points out, so long as you can think of a good name for the logic, this sets up Consolidate Conditional Expression. Which might look like this:
def set_tenant
if tenant_included
current_account = current_user.tenant
set_current_tenant(current_account)
else
set_current_tenant(nil)
end
end
def tenant_included
return current_user
&& current_user.tenant_id.present?
&& current_user.tenants.include?(current_user.tenant)
end