Reputation: 175
I'm trying to refactor a controller with the following logic. :
def recover_password
if params[:login].present?
if User.exists?(id: params[:login])
render plain: "Recover by id" status: :ok
elsif Utils.is_email?(params[:login])
render plain: "Recover by email" status: :ok
else
render plain: "Email not found" status: :unauthorized
end
else
render plain: "Login not found" status: :unauthorized
end
end
I tried to send business logic to the User
model, but I do not know if it's a good alternative:
def recover_password
result = User.recover_password(params)
render plain: result status: :status
end
What is the best alternative to refactor this code? Send to Model and return the messages? But how to return the message and the status code?
P.S: I can't create another method / action in the controller to separate the ways to recover the password.
Upvotes: 2
Views: 138
Reputation: 4640
Not sure if it is a good idea to add this logic to the User model. You can move it to the controller private method.
def recover_password
result = check_params(params[:login])
render plain: result[:message], status: result[:status]
end
private
def check_params(login)
return { message: "Login not found", status: :unauthorized } if login.blank?
return { message: "Recover by id", status: :ok } if User.exists?(id: login)
return { message: "Recover by email", status: :ok} if Utils.is_email?(login)
{ message: "Email not found", status: :unauthorized }
end
Upvotes: 4