#ruby_on_rails #ruby
Есть консерн:
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
Нужно разделить self.find_for_oauth(auth), чтобы количество строк в методе было хотя
бы 15.
Ответы
Ответ 1
Я бы переписал так: 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Ответ 2
Не злоупотребляйте культом Карго. Если какой-то код работает без разбивки, то пусть работает дальше.
Комментариев нет:
Отправить комментарий