There is a user registration controller:
class UsersController < ApplicationController def new unless current_user @user = User.new else redirect_to root_path, alert: "You are already signed up!" end end def create unless current_user @user = User.new(user_params) if @user.save sign_user_in(@user.auth_token) redirect_to root_path, notice: "Signed up&in!" else render 'new' end else redirect_to root_path, alert: "You are already signed up!" end end private def user_params params.require(:user).permit(:email, :password, :password_confirmation) end end There is also a user login controller for the site:
class SessionsController < ApplicationController def new if current_user redirect_to root_path, alert: "You are already signed in!" end end def create unless current_user user = User.find_by_email(params[:email]) if user && user.authenticate(params[:password]) sign_user_in(user.auth_token) redirect_to root_path, notice: "You have been succussfully signed in!" else flash.now[:alert] = "Wrong E-mail or password" render 'new' end else redirect_to root_path, alert: "You are already signed in!" end end def destroy cookies.delete(:auth_token) redirect_to root_path, notice: "You have been successfully logged out!" end end It is necessary to make it so that an already logged in user cannot get to the registration and login pages (because why should an authorized user log in / register on the site again?).
Immediately I thought to use before_action, but the fact is that my current_user method returns an instance of the User class. I thought to create a method current_user ?, which would return whether the user entered the site or not (boolean value), but then you still have to use the if (unless) / else constructs. And this is not DRY at all. How to correctly solve the situation to remove duplication of code?