ruby-on-rails - 如何在 Ruby 中正确使用 guard 子句

标签 ruby-on-rails ruby guard clause

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

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约定

最佳答案

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

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

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

关于ruby-on-rails - 如何在 Ruby 中正确使用 guard 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31943125/

相关文章:

ruby-on-rails - Rspec - Controller 测试错误 - Paperclip::AdapterRegistry::NoHandlerError: 找不到 "#<File:0x531beb0>"的处理程序

json - JSON 文本必须至少包含两个八位字节

ruby-on-rails - 为什么在dockerizing Rails 应用程序后Guard 没有检测到文件更改?

ruby - Ruby 数组与哈希测试中的堆栈级别太深

guard - LiveReload with Guard 无法工作,尽管它说可以

ruby-on-rails - Rails Guard 正在寻找规范文件夹,但没有规范文件夹

ruby-on-rails - Ruby/Rails Apache2 和 Passenger 设置返回目录列表

ruby-on-rails - .find 或 where 事件记录查询中的条件

ruby-on-rails - 如何在中间件中设置 current_user?

ruby-on-rails - 如何在 Mac 上更新 SQLite?