How to break the code so the MethodLength is at least 15



  • There's a conservative:

    module Omniauthable
      extend ActiveSupport::Concern
      included do
        def self.find_for_oauth(auth)
          authorization = Authorization.where(provider: auth.provider, uid: auth.uid.to_s).first
          return authorization.user if authorization
    
      if auth.info.try(:email)
        email = auth.info[:email]
      else
        return false
      end
    
      user = User.where(email: email).first
      if user
        user.create_authorization(auth)
      else
        password = Devise.friendly_token[0, 20]
        user = User.new(email: email,
                        password: password,
                        password_confirmation: password)
        if user.valid?
          user.save!
          user.create_authorization(auth)
        else
          return false
        end
      end
      user
    end
    
    def create_authorization(auth)
      authorizations.create(provider: auth.provider, uid: auth.uid)
    end
    

    end
    end

    We need to split up. self.find_for_oauth(auth)that the number of lines in the method is at least 15.



  • I'd rewrite that:

    module Omniauthable
      extend ActiveSupport::Concern
      included do
        def self.find_for_oauth(auth)
          authorization = Authorization.where(provider: auth.provider, uid: auth.uid.to_s).first
          if authorization
            authorization.user
          else
            @email = auth.info.try(:email)
            find_user # ищем пользователя
            create_user unless @user # если не находим, то создаем
            auth_user(auth) # пытаемся авторизовать и возвращаем либо nil либо пользователя
          end
        end
    
    def create_authorization(auth)
      authorizations.create(provider: auth.provider, uid: auth.uid)
    end
    private # скрываем служебные методы
    
    def self.find_user
      @user = User.where(email: @email).first if @email
    end
    
    def self.create_user
      password = Devise.friendly_token[0, 20]
      udata = {
        email: @email,
        password: password,
        password_confirmation: password
      }
      user = User.create(udata) # здесь происходит валидация и сохранение
      @user = user if user.errors.count == 0 # если после создания нет ошибок, то объявляем переменную экземпляра
    end
    
    def self.auth_user(auth)
      if @user # если в предыдущих методах был найден/создан пользователь, если @user = nil(не существует, то nil вернется из метода)
        @user.create_authorization(auth)
        @user
      end
    end
    

    end
    end




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2