重构代码以减少分配分支条件的大小

时间:2019-11-29 09:50:18

标签: ruby-on-rails ruby ruby-on-rails-5

我正在开发Rails Web应用程序。但是当我运行rubocop来检查代码时。它说以下方法的ABC(分配分支条件)大小太大。当我是Ruby on Rails的新手时,有人可以给我一些建议来重构此代码块吗?有关更多详细信息,我正在实现允许用户通过facebook或google等登录的第三方身份验证。

谢谢

  def self.from_omniauth auth, current_user
    identity = Identity.find_by(provider: auth.provider, uid: auth.id)
                       .first_or_initialize
    if identity.user.blank?
      user = current_user || User.find_by("email = ?",
                                          auth["info"]["email"])
      if user.blank?
        user = User.new
        user.password = Devise.friendly_token[0, 10]
        user.name = auth.info.name
        user.email = auth.info.email
        user.picture = auth.info.image
        return user.save(validate: false) if auth.provider == "twitter"

        user.save
      end
      identity.user_id = user.id
      identity.save
    end
    identity.user
  end

2 个答案:

答案 0 :(得分:0)


  def self.from_omniauth auth, current_user
    identity = Identity.find_by(provider: auth.provider, uid: auth.id)
                       .first_or_initialize
    if identity.user.blank?
      user = current_user || User.find_by("email = ?",
                                          auth["info"]["email"])
      create_user(auth) if user.blank?

      identity.user_id = user.id
      identity.save
    end
    identity.user
  end

  def self.create_user(auth)
    user = User.new
    user.password = Devise.friendly_token[0, 10]
    user.name = auth.info.name
    user.email = auth.info.email
    user.picture = auth.info.image
    return user.save(validate: false) if auth.provider == "twitter"

    user.save
  end

您可以尝试尝试。但是,如果实际上需要复杂性,则可以设置注释以忽略该警察# rubocop:disable ABC (Assignment Branch Condition)或警察的实际名称。如果您觉得尺寸设置太小,也可以配置ABC尺寸

答案 1 :(得分:0)

我没有收到您所说的任何错误,所以您可能应该尝试#rubocop:disable ABC

当我保存它时,它在参数中添加了括号

def self.from_omniauth(auth, current_user)
  identity = Identity.find_by(provider: auth.provider, uid: auth.id)
                     .first_or_initialize
  if identity.user.blank?
    user = current_user || User.find_by("email = ?",
                                        auth["info"]["email"])
    if user.blank?
      user = User.new
      user.password = Devise.friendly_token[0, 10]
      user.name = auth.info.name
      user.email = auth.info.email
      user.picture = auth.info.image
      return user.save(validate: false) if auth.provider == "twitter"

      user.save
    end
    identity.user_id = user.id
    identity.save
  end
  identity.user
end