jeudi 25 juin 2015

Rails controller params conditionals - how to do this cleanly

I'm need to check a bunch of conditions in a controller method. 1) it's a mess and 2) it's not even hitting the right redirects.

def password_set_submit
  password_check = /^(?=.*[a-z]{1,})(?=.*[A-Z]{1,})(?=.*\d{1,}){8,}.+$/

  @user = User.find(session[:id])
    if params[:password] && params[:password_confirmation] && params[:username] && params[:old_password]
        if params[:password] == params[:password_confirmation] && params[:password] =~ password_check

          # do some api stuff here

        if @user.save
          flash[:success] = 'Password updated.'
          redirect_to login_path and return
        end
      end
      if params[:password] != params[:password_confirmation]
        flash[:error] = 'Passwords did not match.'
        redirect_to password_set_path and return
      end
      if params[:password] == params[:password_confirmation] && params[:password] !~ password_check
        flash[:error] = 'Passwords did not match password criteria.'
        redirect_to password_set_path and return
      end
    end
  else
    flash[:error] = 'Please fill all inputs.'
    redirect_to password_set_path and return
  end
end

This needs to do the following:

1) If less than four params submitted, redirect and display 'Fill all inputs'

2) If password and password confirmation don't match each other, redirect and display 'Password did not match'

3) If password and password confirmation match each other but do not match criteria, redirect and display 'Passwords did not match criteria'

4) If password and password confirmation match each other and match criteria, make api call and redirect to login

I'm out of if/else ideas and I hope cleaning this up will help me nail the redirects correctly.

Aucun commentaire:

Enregistrer un commentaire