How to correctly use guard clause in Ruby

限于喜欢 提交于 2019-12-08 15:53:16

问题


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

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


回答1:


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 && current_user.role == 'admin'

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


来源:https://stackoverflow.com/questions/31943125/how-to-correctly-use-guard-clause-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!