如何在 Ruby 中正确使用保护子句 [英] How to correctly use guard clause in Ruby

查看:47
本文介绍了如何在 Ruby 中正确使用保护子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本示例中使用保护子句的正确方法是什么?

What is the correct way to use the guard clause in this sample?

def require_admin
  unless current_user && current_user.role == 'admin'
    flash[:error] = "You are not an admin"
    redirect_to root_path
  end        
end

在尝试使用这些重写时,我不知道将 flash 消息放在哪里 https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals 约定

I don't know where to put flash message when trying to rewrite using these https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals conventions

推荐答案

您可以在此处使用 return 语句.本质上,如果满足这些条件, 方法不需要继续,因此您可以提前退出.

You can use the return statement here. Essentially, there is no need for the method to continue if those conditions are met, so you can bail out early.

def require_admin
  return if current_user&.role == 'admin'

  flash[:error] = 'You are not an admin'
  redirect_to root_path
end

这篇关于如何在 Ruby 中正确使用保护子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆