如何在rails中优化以下代码段

时间:2018-01-17 12:13:29

标签: ruby-on-rails ruby

此代码段将在登录后重定向到预定义页面。 现在我需要传递一个参数,考虑条件是

agreed_user = current_user.has_agreed_to_privacy_policy?

我写了以下代码。我需要最优化的代码段。

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

1 个答案:

答案 0 :(得分:3)

除逻辑本身外,您可以使用return使用所谓的guard clause来避免多个嵌套的if / else语句:

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