如何在Ruby中正确使用guard子句
在此示例中使用保护条款的正确方法是什么?
def require_admin unless current_user && current_user.role == 'admin' flash[:error] = "You are not an admin" redirect_to root_path end end
尝试使用这些https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals惯例重写时,我不知道在哪里放flash消息
您可以在此处使用return
语句。 基本上, if
满足这些条件,则不需要继续该方法,因此您可以提前纾困。
def require_admin return if current_user && current_user.role == 'admin' flash[:error] = "You are not an admin" redirect_to root_path end