Search code examples
ruby-on-railsrubyruby-on-rails-5

Refactor the code to reduce Assignment Branch Condition size


I am developing a Rails web application. But when I run rubocop to check the code. It said that the ABC (Assignment Branch Condition) size of the method below is too high. While I'm a newbie in Ruby on Rails, can someone give me some advice to refactor this block of code? For more details, I am implementing the third party authentication which allows user to sign in by facebook or google, etc.

Thank you

  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

Solution

  • 
      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
    

    Is something you can try. But if the complexity is actually needed you can set a comment to ignore that cop # rubocop:disable ABC (Assignment Branch Condition), or whatever the actual name of the cop is. Also you can configure the ABC size if you feel the size set is too low