ADMAT Bandara
ADMAT Bandara

Reputation: 61

How to optimize the following code segment in rails

This code segment will redirect to the predefined page after sign in. Now I need to pass a parameter considering a condition which is

agreed_user = current_user.has_agreed_to_privacy_policy?

I wrote the following code. I need the best optimized code segment to this.

def index
 if current_user
   agreed_user = current_user.has_agreed_to_privacy_policy?
   diary_count = current_user.diaries.count
   if diary_count == 0
     redirect_to new_diary_path
   elsif diary_count == 1
     unless agreed_user
       redirect_to diary_path(current_user.diaries.first, params: {a: :b})
     else
       redirect_to current_user.diaries.first
     end
   else
     redirect_to diaries_path(params: {a: :b})
   end
 else
   unless agreed_user
     redirect_to login_path(params: {a: :b})
   else
     redirect_to login_path
   end
 end
end

Upvotes: 0

Views: 55

Answers (1)

nattfodd
nattfodd

Reputation: 1890

Besides the logic itself, you can avoid multiple nested if/else statements by using so-called guard clause, using return:

def index
  return redirect_to(login_path) unless current_user

  diary_count = current_user.diaries.count
  return redirect_to(new_diary_path) if diary_count.zero?
  return redirect_to(diaries_path(params: {a: :b})) if diary_count > 1

  if current_user.has_agreed_to_privacy_policy?
    redirect_to current_user.diaries.first
  else
    redirect_to diary_path(current_user.diaries.first, params: {a: :b})
  end
end

Upvotes: 3

Related Questions