Skip to content

Instantly share code, notes, and snippets.

@tuxayo
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuxayo/9e76ec71206d3063e491 to your computer and use it in GitHub Desktop.
Save tuxayo/9e76ec71206d3063e491 to your computer and use it in GitHub Desktop.
Ce que j'ai obtenu après avoir refactoré autant que je pouvais à l'aide d'exceptions pour supprimer les if imbriqués
def change_password
@user = get_and_authorize_user
@user_input = params.require(:user)
begin
check_old_password_match
check_new_password_confirmation_match
@user.password = @user_input['password']
save_user
redirect_to root_path, :notice => 'Mot de passe mis à jour'
rescue PasswordExeception => exeception
error_message_and_retry exeception.message
end
end
private
def get_and_authorize_user
user = User.find(params[:id])
authorize! :update, user
return user
end
def check_old_password_match
if not @user.valid_password?(@user_input['old_password'])
raise PasswordExeception, 'messages.users.invalid_old_password'
end
end
def check_new_password_confirmation_match
if not @user_input['password'] == @user_input['password_confirmation']
raise PasswordExeception, 'messages.users.password_dont_match'
end
end
def save_user
user_saved_successfully = @user.save
if not user_saved_successfully
raise PasswordExeception, 'activerecord.errors.models.user.attributes.password.too_short'
end
end
def error_message_and_retry(error_message)
flash[:error] = t(error_message)
render :password
end
class PasswordExeception < Exception
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment