Skip to content

Instantly share code, notes, and snippets.

@tuxayo
Last active August 29, 2015 14:03

Revisions

  1. tuxayo revised this gist Jul 9, 2014. No changes.
  2. tuxayo revised this gist Jul 9, 2014. No changes.
  3. tuxayo revised this gist Jul 9, 2014. No changes.
  4. tuxayo created this gist Jul 3, 2014.
    49 changes: 49 additions & 0 deletions refactor_exceptions.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    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