如何防止过多的if-else条件

Chr*_*ung 2 ruby if-statement coding-style ruby-on-rails

我有控制器来控制用户是否可以租用产品.我有很多条件要检查,每个都有不同的结果.我有太多的if else陈述.我想知道我可以遵循哪种设计模式使其更具可读性.

if current_user
  if rental_valid?
    if current_user.approved
      if eligible_to_use?(product_id)
        # redirect_to payment
      else 
        # redirect_to :back
        # alert not eligible
      end 
    else
      # redirect_to verify_path
    end 
  else
    # redirect_to :back
    # alert, rental not valid
  end 
else
  # redirect_to login_path
end
Run Code Online (Sandbox Code Playgroud)

saw*_*awa 5

假设这是一种方法:

return redirect_to login_path unless current_user
return redirect_to(:back; alert, rental not valid) unless rental_valid?
return redirect_to verify_path unless current_user.approved
return redirect_to(:back; alert not eligible) unless eligible_to_use?(product_id)
return redirect_to payment
Run Code Online (Sandbox Code Playgroud)

更换returnbreak,等等.如果需要的环境相匹配.