else语句或返回ruby

时间:2014-03-31 23:09:00

标签: ruby if-statement return

我有下一个方法:

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风格,或者最好是一般。

1 个答案:

答案 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