我有下一个方法:
def self.authorize(auth_data)
provider = Provider.find_or_create_by(name: auth_data['name'], uid: auth_data['uid'])
if provider.user.present?
provider.user
else
user = User.find_or_create_with_oauth(auth_data['info'])
provider.update(user: user)
user
end
end
我可以用if-else
替换if-return
条件:
def self.authorize(auth_data)
provider = Provider.find_or_create_by(name: auth_data['name'], uid: auth_data['uid'])
return provider.user if provider.user.present?
user = User.find_or_create_with_oauth(auth_data['info'])
provider.update(user: user)
user
end
我不知道什么是ruby
风格,或者最好是一般。
答案 0 :(得分:5)
你也可以考虑:
def self.authorize(auth_data)
provider = Provider.find_or_create_by(name: auth_data['name'], uid: auth_data['uid']
provider.update(user: User.find_or_create_with_oauth(auth_data['info'])) unless provider.user.present?
provider.user
end
或者,您可能会发现这更具可读性:
def self.authorize(auth_data)
provider = Provider.find_or_create_by(name: auth_data['name'], uid: auth_data['uid'])
unless provider.user.present?
user = User.find_or_create_with_oauth(auth_data['info'])
provider.update(user: user)
end
provider.user
end