Last active
June 21, 2016 21:09
-
-
Save saroar/065029a05e79d086d71f95270cc55be9 to your computer and use it in GitHub Desktop.
self.from_omniauth(auth, organisation) REFACTOR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 3. Please refactor User#from_omniauth method. Currently it's hard to read. Please make it more clear. | |
def self.from_omniauth(auth, organization) | |
user = User.where(provider: auth.provider, uid: auth.uid).first | |
if user | |
return user | |
else | |
registered_user = User.where(email: auth.info.email).first | |
if registered_user | |
return registered_user | |
else | |
user = User.create( | |
provider: auth.provider, | |
uid: auth.uid, | |
name: auth.info.name, | |
email: auth.info.email, | |
password: Devise.friendly_token[0, 20], | |
organization: organization | |
) | |
end | |
end | |
end | |
# 1st refactor | |
def self.from_omniauth(auth, organization) | |
user = User.where(provider: auth.provider, uid: auth.uid).first | |
registered_user = User.where(email: auth.info.email).first | |
return user if user | |
return registered_user if registered_user | |
User.create( | |
provider: auth.provider, | |
uid: auth.uid, | |
name: auth.info.name, | |
email: auth.info.email, | |
password: Devise.friendly_token[0, 20], | |
organization: organization | |
) | |
end |
Final code
class OmniauthUser
attr_reader :auth, :organization
def initialize(auth, organization)
@auth = auth
@organization = organization
end
def find_or_create
if omniauth_user
omniauth_user
elsif registered_user
registered_user
else
create_omniauth_user
end
end
private
def omniauth_user
User.where(provider: auth.provider, uid: auth.uid).first
end
def registered_user
User.where(email: auth.info.email).first
end
def create_omniauth_user
User.create(
provider: auth.provider,
uid: auth.uid,
name: auth.info.name,
email: auth.info.email,
password: Devise.friendly_token[0, 20],
organization: organization
)
end
end
Saw your question on gitter, any reason why you aren't simply using the default in the Devise README on OmniAuth?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
3rd Version