patternrubyrailsMinor
Rails authentication checks
Viewed 0 times
railsauthenticationchecks
Problem
I have this
Now, I could simply this further by moving subdomain into a helper method,
But how to I simply these nested conditionals?
authenticate! method where I am trying to retrieve their account based on the subdomain, then find the user. if user is found & their password is matched, we return success, else fail in all other cases. here is the code:def authenticate!
account = Account.find_by(subdomain: subdomain)
if account
u = account.users.find_by email: params["user"]["email"]
if u.nil?
fail!
else
u.authenticate(params["user"]["password"]) ? success!(u) : fail!
end
else
fail!
end
endNow, I could simply this further by moving subdomain into a helper method,
def subdomain
ActionDispatch::Http::URL.extract_subdomains(request.host, 1)
end
def authenticate!
account = Account.find_by(subdomain: subdomain)
if account
u = account.users.find_by email: params["user"]["email"]
if u.nil?
fail!
else
u.authenticate(params["user"]["password"]) ? success!(u) : fail!
end
else
fail!
end
endBut how to I simply these nested conditionals?
Solution
Another view on @tokland solution:
This intention is to be as close to "original task explained in common English" as possible. And
def authenticate!
return fail! unless account = Account.find_by(subdomain: subdomain)
return fail! unless user = account.users.find_by(email: params["user"]["email"])
return fail! unless user.authenticate(params["user"]["password"])
success! user
endThis intention is to be as close to "original task explained in common English" as possible. And
return keyword allows me to do that.Code Snippets
def authenticate!
return fail! unless account = Account.find_by(subdomain: subdomain)
return fail! unless user = account.users.find_by(email: params["user"]["email"])
return fail! unless user.authenticate(params["user"]["password"])
success! user
endContext
StackExchange Code Review Q#31619, answer score: 8
Revisions (0)
No revisions yet.